如果只是单纯的文件上传下载还是比较简单的。其代码如下:
文件上传:
@PostMapping("/uploadFile")
@ApiOperation("上传报告文件")
public ResponseResult uploadAudio(@RequestParam(value = "file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseResult.failed("文件不能为空");
}
//文件地址不存在,则创建
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
//文件后缀
String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//if (".mp3".equals(prefix) || ".m4a".equals(prefix) || ".wav".equals(prefix)) {
// String fileName = UUID.randomUUID().toString().replaceAll("-", "") + prefix;
String fileName = file.getOriginalFilename();
File newFile = new File(path + fileName);
log.info("上传路径:" + path);
log.info("文件名:" + fileName);
try {
file.transferTo(newFile);
// request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+
String url = dbPath + fileName;
Map<String,Object> map=new HashMap<>();
map.put("url",url);
map.put("name",fileName);
return ResponseResult.ok(map, "上传成功");
} catch (IOException e) {
e.printStackTrace();
return ResponseResult.failed("上传失败");
}
// }
// return ResponseResult.failed("文件格式不符合要求");
}
文件下载:
@GetMapping("/exportFile")
@ApiOperation("下载文件")
public void exportQualityReport(@RequestParam("id") Integer id,HttpServletResponse response)throws IOException{
InputStream inputStream = null;
ServletOutputStream outputStream = null;
if (id!=null){
QualityReportVo vo=reportService.getById(id);
if (vo!=null){
try {
String fileName = vo.getFileName();
String path1 =locationPre+vo.getReportLocation();
Resource resource = new DefaultResourceLoader().getResource("file:" + path1);
FileConvertUtil.responseInit(response, fileName);
inputStream = resource.getInputStream();
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
throw new IOException("下载错误");
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
throw new CustomException("下载错误");
}
}
}else {
throw new IOException("文件id不存在");
}
}else {
throw new CustomException("id不能为空");
}
}
忘记补上重要的一点了,就是设置下载的规则,也就是编码呐,以哪种形象下载呐
/** * 设置文件下载规则 * * @param response * @param fileName */ public static void responseInit(HttpServletResponse response, String fileName) { response.reset(); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)); response.setContentType("application/octet-stream; charset=utf-8"); response.setCharacterEncoding("UTF-8"); }
路径就用自己上传文件的路径就好,代码里面的路径是因为在存储的时候,只显示相对路径,所以在拿个路径时,需要加上前缀做处理。然后路径我也是在配置文件上面配置好了。