1.下载
1.1 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.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@Controller
public class DownLoadController {
/**基于Servlet进行文件下载
*推荐使用
**/
@RequestMapping("/download")
public String hello(HttpServletRequest request, HttpServletResponse resp) throws Exception {
String realPath = request.getServletContext().getRealPath("/file/1.png");
File f = new File(realPath);
String fileName = f.getName();
//设置响应头 context-disposition就是设置文件下载的打开方式,默认会在网页里面打开
//设置attachment;filename=就是为了以下载的方打开文件
//UTF-8是为了文件名有中文不会乱码
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream is = new FileInputStream(f);
InputStream in = new FileInputStream(realPath);//获取文件输入流
int len = 0;
byte[] buffer = new byte[1024];
//is.available()获取到文件的大小,如果文件过于大 可能会造成内存溢出
// byte[] buffer = new byte[is.available()];
OutputStream os = resp.getOutputStream();
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
return null;
}
//ResponseEntity 可以定制文件的响应内容 响应头 响应状态码
@RequestMapping("/responseEntity")
public ResponseEntity<String> responseEntity(){
String body = "hello world";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Set-Cookie","name=xixi");
return new ResponseEntity<String>(body,httpHeaders, HttpStatus.OK);
}
//基于SpringMvc的文件下载, 不支持缓冲区
//ResponseEntity 可以定制文件的响应内容 响应头 响应状态码
@RequestMapping("/download02")
public ResponseEntity<byte[]> download2(HttpServletRequest request) throws Exception {
String realPath = request.getServletContext().getRealPath("/file/1.png");
File f = new File(realPath);
String fileName = f.getName();
//设置响应头 context-disposition就是设置文件下载的打开方式,默认会在网页里面打开
//设置attachment;filename=就是为了以下载的方打开文件
//UTF-8是为了文件名有中文不会乱码
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream is = new FileInputStream(f);
return new ResponseEntity<byte[]>(new byte[is.available()],httpHeaders,HttpStatus.OK);
}
}
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>