一.引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二.单文件上传
这里文件上传保存路径可以先把路径存到redis缓存中,在下载文件的时候获取文件路径
/**
* 单文件上传
*
*/
@RequestMapping("/upload")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
//判断文件是否为空
if (multipartFile.isEmpty()) {
return "File is not Empty!!";
}
//获取文件名
String filename = multipartFile.getOriginalFilename();
System.out.println("文件名:"+filename);
//获取文件后缀名,进行判断选择要上传的文件类型
String suffixName = filename.substring(filename.lastIndexOf("."));
System.out.println("后缀名:"+suffixName);
//设置存放根路径,可以设置任意存放位置,这里默认存放服务端根目录
String contextPath = request.getServletContext().getRealPath("/res/imgs/");
System.out.println(contextPath);
File file=new File(contextPath);
if (!file.exists()) {
file.mkdirs();
}
//存放数据
File targetFile = new File(contextPath + filename);
//把文件路径存放在缓存中
redisTemplate.opsForValue().set("file",contextPath + filename);
try {
multipartFile.transferTo(targetFile);
return "Success !!!";
} catch (IOException e) {
e.printStackTrace();
}
return "Failure !!!";
}
三.多文件上传
/**
* 多文件上传
*/
@RequestMapping("/manyUp")
public String mannyUploadFile(MultipartHttpServletRequest request) throws IOException {
//获取上传路径
String realPath = request.getServletContext().getRealPath("/res/imgs/");
//创建文件夹
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
// 获取多个文件的map实例
Map<String, MultipartFile> fileMap = request.getFileMap();
Set<String> strings = fileMap.keySet();
for (String key:strings) {
//获取multipartFile 实例
MultipartFile multipartFile = fileMap.get(key);
//获取文件名
String filename = multipartFile.getOriginalFilename();
System.out.println("文件名:"+filename);
//上传文件
multipartFile.transferTo(new File(realPath+filename));
}
return "Suceess !!!";
}
四.文件下载
用户点击了下载链接之后,首先服务器设置一下参数,然后使用输出输出流将制定路径下的文件进行输出。
/**
* 文件下载
*/
@RequestMapping("/downLoad")
@ResponseBody
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
// String filename="2.xlsx";
// String filePath = "D:/download" ;
File file = new File((String) redisTemplate.opsForValue().get("file"));
String filename = file.getName();
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("----------file download---" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "Success !!";
}
五.测试
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="http://localhost:8080/demo/upload" method="post" enctype="multipart/form-data">
文件选择:
<input type="file" name="file">
<input type="submit">
</form>
<p>文件下载</p>
<form action="http://localhost:8080/demo/downLoad" method="post">
<p><h2>1.png</h2></p>
下载:<input type="submit" />
</form>
</body>
</html>
六.常见问题
文件上传的时候会出现如下错误,这是被限制了上传文件的大小
org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException:
The field fileName exceeds its maximum permitted size of 1048576 bytes.
解决方案:
在配置文件里配置上传文件大小的最大值,单位必须是大写的 MB 或者 KB
spring:
servlet:
multipart:
max-file-size: 50MB
max-request-size: 50MB