@Slf4j @Controller @RequestMapping(value = "/upload") public class JkFileUploadController { private static final String UPLOAD_FILE_PATH = "upload/jk/files"; @Value("${data.attachment}") public String root; @Value("${domain}") public String domain; @Resource private ResourceLoader resourceLoader; /** * 允许上传文件的格式 */ private static final String[] FILE_TYPE = new String[]{".doc", ".ppt", ".pdf", ".xls", ".xlsx", ".gif", ".jpeg", ".bmp", ".jpg", ".png"}; @PostMapping(value = "/jk/files") public ResponseEntity<String> uploadAllFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) { if (file.isEmpty() || !FileValidateUtil.validateType(file, FILE_TYPE)) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } String path = getFilePath(file.getOriginalFilename()); String docUrl = StringUtils.replace(StrUtil.subSuf(path, root.length()), "\", "/"); try { File newFile = new File(path); file.transferTo(newFile); return ResponseEntity.status(HttpStatus.OK).body(domain + docUrl); } catch (IOException e) { log.error("上传文件错误!" + e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } @ResponseBody @RequestMapping(method = RequestMethod.GET, value = "/jk/files/{filename:.+}") public ResponseEntity<?> getFile(@PathVariable String filename) { try { String filePath = StringUtils.replace(Paths.get(root, UPLOAD_FILE_PATH, filename).toString(), "\", "/"); return ResponseEntity.ok(resourceLoader.getResource("file:" + filePath)); } catch (Exception e) { log.error(e.getMessage(), e); return ResponseEntity.notFound().build(); } } private String getFilePath(String sourceFileName) { String baseFolder = root + File.separator + UPLOAD_FILE_PATH; File file = new File(baseFolder); if (!file.isDirectory()) { if (!file.mkdirs()) { log.info("目录创建失败"); } } // 生成新的文件名 String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, "."); return baseFolder + File.separator + fileName; } }