@RequestMapping("/upload") @ResponseBody public String handleFileUpload(HttpServletRequest request) { MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request); List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); System.out.println("files" + files); //接收前端傳過來的字段 //String name = params.getParameter("name"); MultipartFile file = null; //先設置一個數組來裝file路徑 List imgs = new ArrayList(); //設置圖片路徑 private final String UPLOAD_FOLDER = "pic/"; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 獲取圖片的文件名 String fileName = file.getOriginalFilename(); // 獲取圖片的擴展名 String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1); // 新的圖片文件名 = 獲取時間戳+"."圖片擴展名 String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; //圖片路徑 Path path = Paths.get(UPLOAD_FOLDER + newFileName); //System.out.println("lj: " + path); imgs.add(path); //若是沒有files文件夾,則建立 if (!Files.isWritable(path)) { Files.createDirectories(Paths.get(UPLOAD_FOLDER)); } //文件寫入指定路徑 Files.write(path, bytes); } catch (Exception e) { return "圖片上傳失敗 " + i + " => " + e.getMessage(); } } else { return "圖片上傳失敗 " + i + " because the file was empty."; } } return "圖片上傳成功"; }