spring MVC——文件上传和下载

1、文件上传

Spring MVC为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的,Spring使用Commons FileUpload技术实现了一个MultipartResolver的实现类:CommonsMultipartResolver。

2、文件下载

SpringMVC提供了一个ResponseEntity类型,使用它可以很方便地定义返回的HttpHeaders和HttpStatus。

3、实现代码

添加依赖

    <!-- 文件上传 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

FileController

package com.etc.controller;

import org.apache.commons.io.FileUtils;
import org.omg.CORBA.Request;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class FileController {

    @RequestMapping("/uploadPage")
    public String showUploadPage(){
        return "upload";
    }

    @RequestMapping("/uploadsuccess")
    public String success(){
        return "uploadsuccess";
    }

    @RequestMapping("/upload")
    public String upload(HttpServletRequest req,
                         @RequestParam("files") MultipartFile[] files) throws IOException {
        //得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
        String savePath = req.getServletContext().getRealPath("/WEB-INF/upload");
        File dir = new File(savePath);
        //判断上传文件的保存目录是否存在
        if(!dir.exists()){
            System.out.println(savePath+"目录不存在,需要创建");
            //创建目录
            dir.mkdir();
        }
        for(MultipartFile file : files){
            if(!file.isEmpty()){
                System.out.println(file.getName() + "," + file.getOriginalFilename());
                file.transferTo(new File(savePath+File.separator+file.getOriginalFilename()));
            }
        }
        return "redirect:uploadsuccess";
    }

    @RequestMapping("todownload")
    public String todownload() {
            return "download";
        }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest req,
                                           @RequestParam String filename) throws IOException {
        //下载文件路径
        String path = req.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(path+File.separator+filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名,解决中文名称乱码问题
        //String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");

        //通知浏览器以attachment(下载方式)打开 import java.net.URLEncoder
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename,"UTF-8"));
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
}

upload


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
        <%--文件1多文件上传--%>
        文件1:<input type="file" name="files" multiple="multiple"/></br></br>
        <%--文件2单文件上传--%>
 <%--       文件2:<input type="file" name="files"/><br><br>--%>
        <input type="submit" value="上传">
    </form>
</body>
</html>

uploadseccess

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
文件上传成功!
</body>
</html>

download

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="download?filename=oa.txt">oa.txt</a>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82589847