案例一
引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
自定义html页面
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="text-align: center">
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
方法一
package com.yuan.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author kuai
*/
@Controller
public class FileController {
@GetMapping("/toupload")
public String test(){
return "upload";
}
@ResponseBody
@PostMapping("/upload")
public String upload(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
//文件存放的路径
File file1 = new File("F://我的软件/其他/images/" + filename);
file.transferTo(file1);
return "ok";
}
}
注意: 本事实例使用了模板引擎
方法二
//文件保存路径
private final String filepathDir = "F://我的软件/其他/images/";
@PostMapping("/upload")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
//旧的文件名称
String oldfilename = file.getOriginalFilename();
//获取文件扩展名
String extname = oldfilename.substring(file.getOriginalFilename().lastIndexOf("."));
//防止重名
String newfliename = UUID.randomUUID().toString() + extname;
//返回是整个文件的大小
Integer n= FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filepathDir + newfliename)));
long size = file.getSize();
if(n!=size){
return "文件上传失败!";
}
return "文件上传成功!";
}
文件下载
//根据文件名下载文件
@GetMapping("/down")
public void downFile(String openStyle,String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
//打开方式(inline,attachment)
openStyle=openStyle==null?"attachment":openStyle;
FileInputStream fis = new FileInputStream(new File(filepathDir, name));
ServletOutputStream os=response.getOutputStream();
response.setHeader("Content-disposition",openStyle+";filename"+ URLEncoder.encode(name,"UTF-8"));
IOUtils.copy(fis,os);
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(os);
}
上传视频遇到的问题
文件大小受限:
上传文件超过20MB之后会报错,如下:
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (815792344) exceeds the configured maximum (10485760)
解决方案:
- application.yml 文件中添加
spring:
thymeleaf:
cache: false
servlet:
multipart:
max-file-size: 640MB
max-request-size: 1024MB
- 如果还是不可用则自定义一个配置类 ,在类上加入@Configuration 注解,配置如下的信息 :
@Configuration
public class MutipartFileConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//factory.setMaxFileSize(1024);
//单个文件最大 KB,MB
factory.setMaxFileSize(DataSize.parse("640MB")); //655360 kb
/// 设置总上传数据总大小
factory.setMaxRequestSize(DataSize.parse("10240MB")); //1048576 kb
return factory.createMultipartConfig();
}
}
- 再次启动项目即可使用
视频下载
上述的文件下载方法亦可使用
解决视频下载无后缀名 无法打开播放的问题
//根据文件名下载文件
@RequestMapping("/down")
public void downFile(String open, @RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
//打开方式(inline,attachment)
String openStyle= open==null?"attachment":open;
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", openStyle+";filename=" + URLEncoder.encode(fileName, "UTF-8"));
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(new File(filepathDir, fileName));
//创建输出流
OutputStream out = response.getOutputStream();
//创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
while((len=in.read(buffer))>0){
//输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
//关闭文件输入流
in.close();
//关闭输出流
out.close();
}
删除文件(根据文件名)
@GetMapping("/delet")
@ResponseBody
public String deletFile(@RequestParam("fileName") String fileName){
return FileSystemUtils.deleteRecursively(new File(filepathDir + fileName));
}