1 public class SpringUploadUtil { 2 3 4 /*** 5 * 上傳圖片後返回文件名稱用於存儲數據庫 6 * @author MRC 7 * @date 2019年4月8日上午11:22:54 8 * @return 9 */ 10 public static String uploadPics(List<MultipartFile> file){ 11 12 int index = 0; 13 StringBuffer sb = new StringBuffer(); 14 15 for (MultipartFile multipartFile : file) { 16 if (file.isEmpty()) { 17 continue; 18 } 19 try { 20 //工具類生成文件名 21 String fileName = FileCreateNameUtils.toCreateName(); 22 //獲取文件後綴名 23 String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".")); 24 File f = new File("D:\\upload\\"+fileName+fileType); 25 if (f.exists()) { 26 //判斷這個文件是否存在,若存在則變換文件名 防止覆蓋 27 fileName = FileCreateNameUtils.toCreateName(); 28 } 29 byte[] bytes = multipartFile.getBytes(); 30 Path path = Paths.get("upload/" + fileName+fileType); 31 //寫入磁盤 32 Files.write(path, bytes); 33 34 sb.append(StaticUtils.UPLOAD+fileName+fileType); 35 index++; 36 if (file.size() != index ) { 37 sb.append(","); 38 } 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 44 return sb.toString(); 45 }
通過工具類圖片上傳後,返回的字符串是用逗號分隔的圖片上傳後的路徑!html
舉個栗子: upload/2019041615094470712493.jpg,upload/2019041615094470712456.jpg數據庫
public class FileCreateNameUtils { public static final String numberChar = "0123456789"; /*** * 文件名生成工具類 */ public static String toCreateName() { return getNowDatetoString() + generateNum(10); } /*** * 生成日期字符串 yyyyMMddHHmm * * @author MRC * @date 2019年4月16日下午2:19:37 * @return */ public static String getNowDatetoString() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm"); String dateString = formatter.format(currentTime); return dateString; } /*** * 生成隨機數 * @author MRC * @date 2019年4月16日下午2:21:06 * @param len * @return */ public static String generateNum(int len) { StringBuffer sb = new StringBuffer(); Random random = new Random(); for (int i = 0; i < len; i++) { sb.append(numberChar.charAt(random.nextInt(numberChar.length()))); } return sb.toString(); }
@PostMapping("orderComment") @ResponseBody public Map<String, Object> orderComment(HttpServletRequest request){ Map<String, Object> map = new HashMap<>();
// 從前臺的請求當中取出 file文件類型 List<MultipartFile> list = ((MultipartHttpServletRequest)request).getFiles("file"); String pics = null; if (list.size() != 0) { //上傳圖片 調用工具類上傳 返回上傳後文件的名字 pics = SpringUploadUtil.uploadPics(list); }
// pics = "upload/2019041615094470712493.jpg,upload/2019041615094470712456.jpg"
}
<html> <body> <h1>Spring Boot file upload example</h1> <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="file" name="file" /><br/><br/> <input type="submit" value="Submit" /> </form> </body> </html>