文件上传:
代码:
controller
@PostMapping(value = "/uploadAttachment")
@ApiOperation("添加附件")
@ApiImplicitParam(name = "attachFile", value = "附件", dataType = "MultipartFile")
public void uploadAttachment(MultipartFile attachFile) throws Exception {
attachmentService.uploadAttachment(attachFile);
}
service
@Override
public void uploadAttachment(MultipartFile attachFile) throws IOException {
log.info("enter uploadAttachment {}", attachFile.getOriginalFilename());
//原文件全名
String originalFilename = attachFile.getOriginalFilename();
//系统存储的名称
String fileStoreName ="newfile";
//文件大小
long fileSize = attachFile.getSize();
int indexOf = originalFilename.lastIndexOf(".");
//文件名
String fileName = originalFilename.substring(0, indexOf);
//拓展名
String fileExt = originalFilename.substring(indexOf + 1);
String dir = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath() + "attachment";
//存储的全路径
String fileStorePath = dir + "/" + fileStoreName;
//判断文件夹是否存在,存在就不需要重新创建,不存在就创建
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();
}
//转换成对应的文件存储,new File第一个参数是目录的路径,第二个参数是文件的完整名字
attachFile.transferTo(new File(file, fileStoreName));
log.info("finish uploadAttachment");
}
测试:
使用postman测试
Content-Type:multipart/form-data
文件下载:
controller
@PostMapping(value = "/downloadAttachment")
@ApiOperation("下载附件")
@ApiImplicitParam(name = "attachId", value = "附件id", dataType = "Long")
public void downloadAttachment(@RequestParam("attachId") Long attachId, HttpServletResponse response) throws Exception {
attachmentService.downloadAttachment(attachId, response);
}
service
@Override
public void downloadAttachment(Long attachId, HttpServletResponse response) throws IOException {
log.info("enter downloadAttachment {}", attachId);
TtPartyAttachment attachment = this.baseMapper.selectById(attachId);
//文件存储的位置
String remotePath = attachment.getRemotePath();
//文件全称
String originFullName = attachment.getAttachName() + "." + attachment.getAttachExt();
//附件大小
BigDecimal attachSize = attachment.getAttachSize();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
originFullName = URLEncoder.encode(originFullName, String.valueOf(StandardCharsets.UTF_8));
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + originFullName + ";" + "filename*=utf-8''" + originFullName);
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + attachSize);
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
FileInputStream inputStream = new FileInputStream(remotePath);
InputStream fis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
inputStream.close();
outputStream.write(buffer);
outputStream.flush();
log.info("finish downloadAttachment ");
}
测试