1.下载

1.1 Controller

  1. package com.xixi.controller;
  2. import org.springframework.http.HttpHeaders;
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.*;
  10. import java.net.URLEncoder;
  11. @Controller
  12. public class DownLoadController {
  13. /**基于Servlet进行文件下载
  14. *推荐使用
  15. **/
  16. @RequestMapping("/download")
  17. public String hello(HttpServletRequest request, HttpServletResponse resp) throws Exception {
  18. String realPath = request.getServletContext().getRealPath("/file/1.png");
  19. File f = new File(realPath);
  20. String fileName = f.getName();
  21. //设置响应头 context-disposition就是设置文件下载的打开方式,默认会在网页里面打开
  22. //设置attachment;filename=就是为了以下载的方打开文件
  23. //UTF-8是为了文件名有中文不会乱码
  24. resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  25. InputStream is = new FileInputStream(f);
  26. InputStream in = new FileInputStream(realPath);//获取文件输入流
  27. int len = 0;
  28. byte[] buffer = new byte[1024];
  29. //is.available()获取到文件的大小,如果文件过于大 可能会造成内存溢出
  30. // byte[] buffer = new byte[is.available()];
  31. OutputStream os = resp.getOutputStream();
  32. while ((len = is.read(buffer)) != -1) {
  33. os.write(buffer, 0, len);
  34. }
  35. is.close();
  36. return null;
  37. }
  38. //ResponseEntity 可以定制文件的响应内容 响应头 响应状态码
  39. @RequestMapping("/responseEntity")
  40. public ResponseEntity<String> responseEntity(){
  41. String body = "hello world";
  42. HttpHeaders httpHeaders = new HttpHeaders();
  43. httpHeaders.set("Set-Cookie","name=xixi");
  44. return new ResponseEntity<String>(body,httpHeaders, HttpStatus.OK);
  45. }
  46. //基于SpringMvc的文件下载, 不支持缓冲区
  47. //ResponseEntity 可以定制文件的响应内容 响应头 响应状态码
  48. @RequestMapping("/download02")
  49. public ResponseEntity<byte[]> download2(HttpServletRequest request) throws Exception {
  50. String realPath = request.getServletContext().getRealPath("/file/1.png");
  51. File f = new File(realPath);
  52. String fileName = f.getName();
  53. //设置响应头 context-disposition就是设置文件下载的打开方式,默认会在网页里面打开
  54. //设置attachment;filename=就是为了以下载的方打开文件
  55. //UTF-8是为了文件名有中文不会乱码
  56. HttpHeaders httpHeaders = new HttpHeaders();
  57. httpHeaders.set("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  58. InputStream is = new FileInputStream(f);
  59. return new ResponseEntity<byte[]>(new byte[is.available()],httpHeaders,HttpStatus.OK);
  60. }
  61. }

1.2 jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/download">Servlet下载文件</a>
  <p></p>
  <a href="${pageContext.request.contextPath}/download02">SpringMvc下载文件</a>
  </body>
</html>

2.上传

Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的。Spring 用 Jakarta Commons FileUpload 技术实现了一个 MultipartResolver 实现类:CommonsMultipartResovler
Spring MVC 上下文中默认没有装配 MultipartResovler,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 MultipartResolver。

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-mvc</artifactId>
        <groupId>com.xixi</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-mvc-file</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
           <dependency>
             <groupId>commons-fileupload</groupId>
             <artifactId>commons-fileupload</artifactId>
             <version>1.4</version>
           </dependency>
    </dependencies>

</project>

2.2 spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">


    <!-- 包扫描 -->
    <context:component-scan base-package="com.xixi"></context:component-scan>


    <!-- 默认视图解析器, 配置前缀和后缀 简化我们的开发-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" name="viewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="#{1024*1024*10}"></property>
    </bean>


</beans>

2.3 Controller

package com.xixi.controller;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class UploadController {




    //multipartResolver 文件上传
    @PostMapping("/upload")
    public String upload(String desc, MultipartFile myfile,HttpServletRequest request) throws IOException {
        System.out.println(desc);
        System.out.println(myfile.getOriginalFilename());
        myfile.transferTo(new File("/Users/yangkang/"+myfile.getOriginalFilename()));
        return "success";
    }



    //multipartResolver 文件上传
    @PostMapping("/upload02")
    public String upload(String desc, MultipartFile[] myfile) throws IOException {
        System.out.println(desc);
        for (MultipartFile multipartFile : myfile) {
            multipartFile.transferTo(new File("/Users/yangkang/"+multipartFile.getOriginalFilename()));

        }
        return "success";
    }



    //multipartResolver 文件上传
    @PostMapping("/upload03")
    public String upload03(String desc, MultipartFile[] myfile) throws IOException, InterruptedException {
        System.out.println(desc);

        for (MultipartFile multipartFile : myfile) {
            Thread thread = new Thread(() -> {
                try {
                    multipartFile.transferTo(new File("/Users/yangkang/" + multipartFile.getOriginalFilename()));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            thread.start();
            thread.join();

        }
        return "success";
    }


}

2.4 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/download">Servlet下载文件</a>
  <p></p>
  <a href="${pageContext.request.contextPath}/download02">SpringMvc下载文件</a>

  <form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload">
    <p></p>
    <input type="text" name="desc" />文件描述
    <p></p>
    <input type="file"  name="myfile"/>
    <p></p>
    <input type="submit"/>
  </form>

  <p>多文件上传================================</p>


  <form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload02">
    <p></p>
    <input type="text" name="desc" />文件描述
    <p></p>
    <input type="file"  name="myfile" multiple/>
    <p></p>
    <input type="submit"/>
  </form>

  <p>多线程多文件上传================================</p>


  <form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload03">
    <p></p>
    <input type="text" name="desc" />文件描述
    <p></p>
    <input type="file"  name="myfile" multiple/>
    <p></p>
    <input type="submit"/>
  </form>
  </body>
</html>