配置文件
#uploadFolder 是上传路径,如果部署在linux,把路径改为linux下的
file.uploadFolder=D:/upload/
file.staticAccessPath=/a/file/**
spring.servlet.multipart.enabled=true
#最大上传文件总体积
spring.servlet.multipart.max-request-size=100MB
#当上传多大时,写入硬盘
spring.servlet.multipart.file-size-threshold=1MB
#单个文件最大的体积
spring.servlet.multipart.max-file-size=10MB
1.配置本地路径可以被外网访问
@Configuration
public class UploadFilePathConfig implements WebMvcConfigurer {
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:"+uploadFolder);
}
}
2.文件上传
@Value("${file.uploadFolder}")
private String uploadFolder;
@RequestMapping("fileUpload")
@ResponseBody
public void fileUpload(MultipartFile file){
try{
String filepath = uploadFolder;
File fsupload = new File(filepath);
if(!fsupload.exists()){
fsupload.mkdirs();
}
//将文件名改成uuid的形式
//定义新的文件名
String fileid = UUID.randomUUID().toString();
String ext = FilenameUtils.getExtension(file.getOriginalFilename());
File newUploadFile = new File(filepath,fileid+"."+ext);
//将上传的文件,按指定的名称保存到指定的路径下
file.transferTo(newUploadFile);
}catch (Exception e){
e.printStackTrace();
}
}
3.文件下载
@RequestMapping("fileDownload")
@ResponseBody
public void fileDownload(String filename,HttpServletResponse response){
try{
String filePath = uploadFolder;
File file = new File(filePath+File.separator+filename);
if(file.exists()){
response.setHeader("Content-Type","application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+
new String("图书信息统计表.xlsx".getBytes(StandardCharsets.UTF_8),"ISO8859-1"));
byte []buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream();
int i=0;
while((i=fis.read(buffer))!=-1){
os.write(buffer,0,i);
}
}
}catch (Exception e){
e.printStackTrace();
}
}