文件上传借助于 org.springframework.web.multipart。
SpringBoot 文件上传配置
1 2 3 4 5 6 7
| spring: servlet: multipart: max-file-size: 100MB max-request-size: 200MB
|
Contorller层中的上传接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Autowired private ServerConfig serverConfig;
@PostMapping("/upload") public ResultJson uploadFile(MultipartFile file) throws Exception { try { String filePath = MyConfig.getUploadPath(); String fileName = FileUploadUtils.upload(filePath, file); String url = serverConfig.getUrl() + fileName; Map<String, String> params = new HashMap<>(16); params.put("fileName", fileName); params.put("url", url); return ResultJson.ok(params); } catch (Exception e) { return ResultJson.failure(ResultCode.BAD_REQUEST, e.getMessage()); } }
|
上传工具类中的核心方法
上传方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } }
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNameLength = file.getOriginalFilename().length(); if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); }
assertAllowed(file, allowedExtension); String fileName = extractFileName(file); File desc = getAbsoluteFile(baseDir, fileName); file.transferTo(desc); String pathFileName = getPathFileName(baseDir, fileName); return pathFileName; }
|
构造文件路径和请求路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
public static final String extractFileName(MultipartFile file) { String fileName; String extension = getExtension(file); fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; return fileName; }
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName);
if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } if (!desc.exists()) { desc.createNewFile(); } return desc; }
private static final String getPathFileName(String uploadDir, String fileName) { int dirLastIndex = MyConfig.getProfile().length(); String currentDir = StringUtils.substring(uploadDir, dirLastIndex); String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; return pathFileName; }
|