我这个方法是自己摸索的,不知道是不是好的,没有对文件大小限制目前
1.nginx里面配置下载路径
location ^~/download {
alias /sam/download/;
autoindex on; # 开启目录文件列表
autoindex_exact_size on; # 显示出文件的确切大小,单位是bytes
autoindex_localtime on; # 显示的文件时间为文件的服务器时间
charset utf-8,gbk; # 避免中文乱码
limit_rate 1024k;
}
2.springboot的代码
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Component
public class FileController {
private static final String dirPath = "/sam/download/chat/";
private static final String DOWNLOAD_URL = "https://www.godboy.cn/download/";
@PostMapping("/uploadHeader")
public CommonResult<String> uploadHeader( @RequestParam(value = "imageFile") MultipartFile imageFile) {
if (imageFile == null){
return new CommonResult<>(201, "文件不存在", "");
}
//获取上传的图片格式
String originalFilename = imageFile.getOriginalFilename();
String type= "";
if(originalFilename.contains(".")){
type = originalFilename.substring(originalFilename.lastIndexOf("."));
}else{
type = "";
}
//重命名文件,新建header的文件夹
String fileName = UUID.randomUUID().toString();
File targetFile = new File(dirPath+"header/", fileName+type);
if (!targetFile.exists()) {
targetFile.mkdirs();
} else {
targetFile.delete();
}
//转存到centos
try {
imageFile.transferTo(targetFile);
return new CommonResult<>(200, "success", DOWNLOAD_URL+"header/"+fileName+type);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return new CommonResult<>(201, "文件上传失败", "");
}
}