org.springframework.boot spring-boot-starter-web
# 单个文件最大限制 spring.servlet.multipart.max-file-size=100MB # 整体请求大小限制 spring.servlet.multipart.max-request-size=100MB
文件上传
@PostMapping("/tablePortalDataUpload")
public void tablePortalDataUpload(@RequestParam("file") MultipartFile file, @RequestParam Map params) {
try {
if (!file.isEmpty()) {
String filename = file.getOriginalFilename();//上传文件名
String suffix = filename.substring(filename.lastIndexOf("."));//后缀
String id = UUID.randomUUID().toString().replace("-", "");
String file_name = id + suffix;
File f = new File("/新路径/", file_name);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
//转移文件
file.transferTo(f.getAbsoluteFile());
}
} catch (IOException e) {
e.printStackTrace();
}
}
多文件上传
@PostMapping("/upload")
public void upload(@RequestParam() MultipartFile[] files, @RequestParam Map params) {
try {
for(int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
if (!file.isEmpty()) {
String filename = file.getOriginalFilename();//上传文件名
String suffix = filename.substring(filename.lastIndexOf("."));//后缀
String id = UUID.randomUUID().toString().replace("-", "");
String file_name = id + suffix;
File f = new File("/新路径/", file_name);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
//转移文件
file.transferTo(f.getAbsoluteFile());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
文件下载
@PostMapping("/tablePortalDataDownload")
public void tablePortalDataDownload(HttpServletResponse response, @RequestParam Map params) {
ServletOutputStream out = null;
FileInputStream fis = null;
try {
// 1、下载文件的路径
File file = new File("文件路径");
//2、下载的文件名
String fileName = file.getName();
//3、设置response的Header
response.addHeader("Content-Length", "" + file.length());
response.addHeader("Content-Type", "application/octet-stream");//任意类型的二进制流数据
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 4、获取下载文件的输入流
fis = new FileInputStream(file);
// 循环取出流中的数据
out = response.getOutputStream();
byte[] buf = new byte[1024 * 1024];
int len;
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}



