SpringBoot 简单文件上传下载
配置文件路径
spring:
servlet:
multipart:
max-file-size: 50MB
max-request-size: 100MB
file:
path: /Users/jisen/Desktop
folder: /files/
文件上传核心代码
package com.demo.studynew;
import cn.hutool.core.io.IoUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@RestController
@RequestMapping("file")
public class FileController {
@Value("${file.path}")
private String filePath;
@Value("${file.folder}")
private String fileFolder;
@PostMapping("upload")
public String upload(@RequestParam("file") MultipartFile file){
String originalFilename = file.getOriginalFilename();
String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
File dest = new File(filePath +fileFolder+ System.currentTimeMillis() + "" + suffixName);
try {
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return fileFolder + dest.getName();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
@GetMapping(value = "download",produces = "application/octet-stream")
public void download(String fileUrl, HttpServletResponse response) {
String filename = null;
try {
filename = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
} catch (Exception e) {
throw new RuntimeException("文件不存在");
}
if (!fileUrl.contains(fileFolder)) {
throw new RuntimeException("文件不存在");
}
fileUrl = fileUrl.split(fileFolder)[1];
File file = new File(filePath + fileFolder + fileUrl);
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}
InputStream is = null;
OutputStream os = null;
try {
response.setHeader("content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8"));
os = response.getOutputStream();
is = new FileInputStream(file);
IoUtil.copy(is, os, 8192);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
IoUtil.close(os);
IoUtil.close(is);
}
}
}
资源映射
package com.demo.studynew;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${file.path}")
private String filePath;
@Value("${file.folder}")
private String fileFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(fileFolder + "**").addResourceLocations("file:" + filePath + fileFolder);
}
}