文件上传
/**
* 文件上传
*
* @param file
* @return
* @throws Exception
*/
@PostMapping("/upload")
public AjaxRequestResult upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
return AjaxRequestResult.error("error", "上传文件不能为空");
}
String fileCode = fileManageService.upload(file);
//生成动态url
String url = MvcUriComponentsBuilder.fromMethodName(FileManageController.class, "showPicture", null, fileCode).buildAndExpand().toString();
return AjaxRequestResult.success(url);
}
测试:
以上说明上传成功,并返回下载的url地址。这里是动态生成url,使用的 MvcUriComponentsBuilder.fromMethodName生成动态的url,可以自动添加服务器ip地址。
文件下载
/**
* 图片下载展示
*
* @param response
* @param fileCode 当时用@PathVariable 来获取value时,如果value中包含‘.’,会丢失部分数据,可以将{filecode} 改成 {fileCode:.+}
* @return
* @throws Exception
*/
@GetMapping("/ShowPicture/{fileCode:.+}")
public StreamingResponseBody showPicture(HttpServletResponse response, @PathVariable String fileCode) throws Exception {
String fileExtension = FilenameUtils.getExtension(fileCode);
response.setContentType("image/" + fileExtension);
response.setHeader("Content-Disposition", "attachment;filename=" + fileCode);
ByteArrayOutputStream stream = fileManageService.download(fileCode);
return outputStream -> outputStream.write(stream.toByteArray());
}
测试
以上用来测试下载,返回的是一个流,直接点击send,会直接展示下载的内容,如果点击send and downlaod 会弹出一个窗体,选择下载的目录,下载到本地。
另外这里需要注意,当使用@PathVariable来获取value值时,传的参数中包含‘.’时,会出现部分数据丢失,没有 ‘.’及其之后的内容,解决方案是将{paramName}改成{paramName:.+}