springmvc上传下载文件

添加:

  <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

*上传:

  1.页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/20 0020
  Time: 11:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<h3>文件上传</h3>
<form action="upload" method="post" enctype="multipart/form-data"> <!--负责上传文件的表单类型必须是:"multipart/form-data"-->
    <table>
       <tr>
            <td>文件描述</td>
            <td><input type="text" name="desc"></td>
       </tr>
        <tr>
            <td>请选择文件:</td>
            <td><input type="file" name="file"></td>
        </tr>
        <tr>
            <td><input type="submit" value="上传"></td>
        </tr>
    </table>
</form>
</body>
</html>

2.控制器:

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Controller
public class FileUploadController {
    @RequestMapping("upload")
    public String uplaod(HttpServletRequest request , @RequestParam("desc") String desc, @RequestParam("file")MultipartFile file, Model model) throws Exception{
        System.out.println(desc);
        //如果文件不为空 ,写入上传路径
        if(!file.isEmpty()) {
            String path = request.getServletContext().getRealPath("/file/");
            model.addAttribute("path",path);
            //上传文件名
            String filename = file.getOriginalFilename();
            File f = new File(path, filename);
            //判断路径是否存在,不存在则创建
            if(!f.getParentFile().exists()){
                f.getParentFile().mkdir();//创建
            }
            //将上传的文件保存在一个目标目录中
            file.transferTo(new File(path+File.separator+filename));
            return "uploadsuccess";
        }else {
            return "error";
        }
    }
}

3.返回页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/20 0020
  Time: 12:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传成功</title>
</head>
<body>
上传成功!<br>
文件保存在:${requestScope.path}
</body>
</html>

* 将文件保存在对象中,并下载

1.接收上传文件的对象Person:

package model;

import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;

public class Person implements Serializable{
    private String name;
    private MultipartFile image;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public MultipartFile getImage() {
        return image;
    }
    public void setImage(MultipartFile image) {
        this.image = image;
    }
}

2.将信息传入控制器的页面:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/20 0020
  Time: 12:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form action="sss" enctype="multipart/form-data" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>请上传头像</td>
            <td><input type="file" name="image"></td>
        </tr>
        <tr>
            <td><input type="submit" value="注册"></td>
        </tr>
    </table>
</form>
</body>
</html>

3.控制器:(两个方法一个对象用于接收上传文件,另一个下载文件)
package controller;

import model.Person;
import org.apache.commons.io.FileUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
public class FileDownLoadController {

    //使用对象接收上传文件,将文件放在对象中。
    @RequestMapping(value = "sss")
    public String sss(HttpServletRequest request, @ModelAttribute Person person , Model model) throws  Exception{
        System.out.println(person.getName());
        //如果文件不是空的,写入上传路径
        if(!person.getImage().isEmpty()){
            String path =  request.getServletContext().getRealPath("/file/");
            //文件上传名
            String fileName = person.getImage().getOriginalFilename();
            File filePath =  new File(path,fileName);
            //判断路径是否存在,不存在创建
            if(!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdir();
            }
            //将上传文件保存在目标对象中
            person.getImage().transferTo(new File(path+File.separator+fileName));
            model.addAttribute("person",person);
            //跳转到下载页面
            return "personInfo";
        }
        return  "error";
    }

    //下载
    @RequestMapping(value = "download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("fileName") String fileName, Model model) throws Exception{
        //下载文件路径
        String downloadPath =  request.getServletContext().getRealPath("/file/");
        File file = new File(downloadPath+File.separator+fileName);
        HttpHeaders httpHeaders = new HttpHeaders();
        //下载显示的文件名,解决中文乱码问题
        String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
        httpHeaders.setContentDispositionFormData("attachment",downloadFileName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
    }
}

4.点击此页面的超链接,进行下载

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/20 0020
  Time: 12:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="download?fileName=${requestScope.person.image.originalFilename}">
    ${requestScope.person.image.originalFilename}
</a>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值