1. Determine the file suffixes, picture suffixes, photo suffixes, and other tools that can be used to upload files

import org.springframework.stereotype.Component; import java.io.File; import java.util.Arrays; import java.util.List; @Component public class FileUtil { public static final List<String> IMAGE_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png"); } import java.util.UUID; public class CommonUtil { public static String getUUID() { String uuid = UUID.randomUUID().toString().replaceAll("-", ""); return uuid; } } import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateUtil { public static final String HH = "HH"; public static final String YYYY_MM_DD = "yyyy-MM-dd"; public static final DateTimeFormatter FORMATTER_HH = DateTimeFormatter.ofPattern(HH); public static final DateTimeFormatter FORMATTER_YYYY_MM_DD = DateTimeFormatter.ofPattern(YYYY_MM_DD); public static String getHH() { return FORMATTER_HH.format(LocalDateTime.now()); } public static String getYYYYMMDD() { return FORMATTER_YYYY_MM_DD.format(LocalDateTime.now()); }}Copy the code

2. Upload interface

@PostMapping("/updateImage.do") public Map<String, String> updateImage(@RequestParam("image") MultipartFile[] multfiles) { Map<String, String> result = new HashMap<>(); If (multfiles.length == 0) {result.put("message", "please select image!" ); return result; } // Final String originalFileName = MultFiles [0].getoriginalFilename (); If (stringutils. isBlank(originalFileName)) {result.put("message", "please select picture!" ); return result; } / / file suffix [. JPG] final String suffix. = originalFileName substring (originalFileName. LastIndexOf (". "). The toLowerCase (); if (! Fileutil.image_extension. contains(suffix)) {result.put("message", "wrong format!" ); return result; } String lastFilePath; String newFileName = CommonUtil.getUUID() + suffix; String folderName = File.separator + "temp" + File.separator; String relativePath = folderName + DateUtil.getYYYYMMDD() + File.separator + DateUtil.getHH(); String filePath = "D:\\file" + relativePath; String fileUrl = null; File targetFile = new File(filePath); if (! targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream out = null; try { lastFilePath = filePath + File.separator + newFileName; out = new FileOutputStream(lastFilePath); out.write(multfiles[0].getBytes()); FileUrl = "http://127.0.0.1:9000" + relativePath + file. separator + newFileName; } catch (Exception e) { e.printStackTrace(); } finally { if (out ! = null) { try { out.flush(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); }} if (fileUrl == null) {result.put("message", "message failed to upload!" ); return result; } result.put("message", "upload success!" ); result.put("url", fileUrl); return result; }Copy the code

3. The upload is successful

Url = > http://127.0.0.1:9000/temp/2019-09-12/14/0eac00b96f134652b34172e84febe8d1.jpgCopy the code