Fork me on GitHub

SpringMVC-11-文件上传和下载

11. 文件上传和下载

准备工作

​ springMVC可以很好的支持文件上传,但是SpringMVC上下文默认没有装配MultipartResolver,因此默认情况下不能处理文件上传工作。如果想实现,必须在上下文配置MultipartResolver

​ 前端表单要求:为了能上传文件,必须使用POST,并将enctype设置为multipart/form-data。浏览器可以把用户选择的文件以二进制数据发送给服务器。

对表单的enctype属性的详细说明

  • application/x-www=form-urlencoded:默认方式,只处理value值,表单域中的值会处理成URL编码。
  • multipart/form-data:二进制流的方式处理表单数据。封装到请求参数中,不会对字符编码。
  • text/plain:除了把空格转换成+号,其他字符不做编码处理,这种方式适合直接通过表单发送邮件。

Apache发布开源的Commons FileUpload组件:

  • Servlet 3.0规范已经提供方法来处理文件上传;
  • SpringMVC提供了更简单的封装;
  • 即插即用的MultipartResolver实现了这个功能;
  • SpringMVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类。

文件上传

  1. 导入文件上传的jar包,commons-fileupload,Maven会自动帮我们导入她的依赖包 commons-io包:

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    
  2. 配置bean:multipartResolver

    【注意!这个bean的id必须是multipartResolver,否则文件会报404】

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--请求的编码格式 必须和jsp的pageEncoding一致-->
        <property name="defaultEncoding" value="utf-8"/>
        <!--上传文件的大小上限 10M-->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
    

CommonsMultipartFile的常用方法:

  • String getOriginalFilename():获取上传文件的原名;
  • InputStream getInputStream():获取文件流
  • void transferTo(File dest):将上传文件保存到一个目录文件
  1. 编写前端页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>$Title$</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath}/upload2" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
    </body>
    </html>
    
  2. Controller

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
        String uploadFilename = file.getOriginalFilename();
    
        if("".equals(uploadFilename)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名:"+uploadFilename);
    
        String path = request.getServletContext().getRealPath("/upload");
    
        File realPath = new File(path);
        if (!realPath.exists())
            realPath.mkdir();
        System.out.println("文件保存地址:"+realPath);
    
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, uploadFilename));
    
        int len=0;
        byte[] buffer = new byte[1024];
        while((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }
    

采用file.Transto来保存上传的文件

  1. 编写Controller

    @RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
    
        File realPath = new File(path);
        if (!realPath.exists())
            realPath.mkdir();
        System.out.println("上传文件保存地址:"+realPath);
    
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
        return "redirect:/index.jsp";
    }
    
  2. 前端表单提交地址修改

  3. 访问提交测试

文件下载

步骤:

  1. 设置response请求头
  2. 读取文件--InputStream
  3. 写出文件--OutputStream
  4. 执行操作
  5. 关闭流
@RequestMapping("/download")
public String downloads(HttpServletResponse response,HttpServletRequest request) throws IOException {
    String path = request.getServletContext().getRealPath("/upload");
    String fileName="基础语法.jpg";

    response.reset();
    response.setCharacterEncoding("UTF-8");
    response.setContentType("multipart/form-data");

    response.setHeader("Content-Disposition",
            "attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
    File file = new File(path, fileName);
    InputStream inputStream = new FileInputStream(file);
    OutputStream outputStream = response.getOutputStream();

    byte[] buffer = new byte[1024];
    int index=0;
    while((index=inputStream.read(buffer))!=-1){
        outputStream.write(buffer,0,index);
        outputStream.flush();
    }
    outputStream.close();
    inputStream.close();
    return null;
}

posted @ 2020-09-16 12:11  CodeHuba  阅读(113)  评论(0编辑  收藏  举报