添加附件和下载附件

上传文件时同时把(文件名 扩展名  文件大小 创建用户id  创建日期 路径 )同时保存到数据库里去

下载时根据相关id查询出(文件名 扩展名  文件大小 创建用户id  创建日期 路径 )再根据(文件名 扩展名  文件大小 创建用户id  创建日期 路径 )里的一些信息下载。

@PostMapping("addAccessory")

@ApiOperation(value = "添加事件附件", notes = "添加事件附件")
@ResponseBody
public ResponseEntity<ActionResponse<EventAccessory>> addAccessory(@RequestParam("file") MultipartFile file, EventAccessory eventAccessory) {
eventService.addEventAccessoryFile(file, eventAccessory);
EventAccessory ea = eventService.addEventAccessory(eventAccessory);
return ActionResponse.ok(ea);

}



public void addEventAccessoryFile(MultipartFile file, EventAccessory eventAccessory) {
String fileNameExtend = file.getOriginalFilename();
String fileName = fileNameExtend.substring(0, fileNameExtend.lastIndexOf("."));
String fileExtend = fileNameExtend.substring(fileNameExtend.lastIndexOf(".") + 1);
String eaName = this.getEventAccessoryName(eventAccessory.getRelatedNumber());
String eaSavePath = ExportExcelUtilsExpand.getRealPath();
File localFile = new File(eaSavePath + File.separator + ACCESSORY_DIRECTORY + File.separator + eaName + "." + fileExtend);
try {
file.transferTo(localFile);
eventAccessory.setName(fileName);
eventAccessory.setFileExtend(fileExtend);
eventAccessory.setFileSize((int)file.getSize());
eventAccessory.setPath(File.separator + ACCESSORY_DIRECTORY + File.separator + eaName + "." + fileExtend);
} catch(IOException e) {
log.error("添加附件失败{}", e);
throw new ExpectedException("添加附件失败");
}

}


public EventAccessory addEventAccessory(EventAccessory eventAccessory) {
/**
* 1,赋值
* 1)创建用户id取自session
* 2)创建日期取自数据库时间
*/
eventAccessory.setUserId(SessionUtil.getCurrentUser().getId());
eventAccessory.setCreateDate(DateUtilsExpand.getDateTime(DateUtilsExpand.yyyy_MM_dd, this.getSysDate()));
return eventAccessoryRepository.save(eventAccessory);

}

扫描二维码关注公众号,回复: 1182142 查看本文章


public static String getRealPath() {
ServletRequest request = ((WebSubject)SecurityUtils.getSubject()).getServletRequest();
HttpSession httpSession = ((HttpServletRequest)request).getSession();
return httpSession.getServletContext().getRealPath("/");

}



@GetMapping("downloadAccessory")
@ApiOperation(value = "下载事件附件", notes = "下载事件附件")
@ResponseBody
public void downloadAccessory(Integer id, HttpServletResponse resp) {
EventAccessory ea = eventService.getEventAccessory(id);
FileUtilsExpand.downloadFile(ea.getPath(), ea.getName() + "." + ea.getFileExtend(), resp);

}



猜你喜欢

转载自blog.csdn.net/m0_38053538/article/details/79855001