spring boot多個圖片上傳
阿新 • • 發佈:2018-12-29
package com.example.demo.controller; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.util.UUID; @RequestMapping("/api/picture") @RestController public class PicUploadController { private static final Logger logger = LoggerFactory.getLogger(PicUploadController.class); //請求訂單列表 @ResponseBody @RequestMapping(value = "/batch/upload", method = RequestMethod.POST) public String getOrderDtl(@RequestParam(value = "file") MultipartFile files[], HttpServletRequest request) { logger.info("圖片批量上傳,files[]=",files); // String uploadPath = request.getSession().getServletContext().getRealPath("/") + "/upload"; String uploadPath = "C:\\test\\upload"; File uploadDirectory = new File(uploadPath); if (uploadDirectory.exists()) { if (!uploadDirectory.isDirectory()) { uploadDirectory.delete(); } } else { uploadDirectory.mkdir(); } //這裡可以支援多檔案上傳 if (files != null && files.length >= 1) { BufferedOutputStream bw = null; try { for (MultipartFile file : files) { String fileName = file.getOriginalFilename(); //判斷是否有檔案且是否為圖片檔案 if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) { //建立輸出檔案物件 File outFile = new File(uploadPath + "/" + UUID.randomUUID().toString()+ getFileType(fileName)); //拷貝檔案到輸出檔案物件 FileUtils.copyInputStreamToFile(file.getInputStream(), outFile); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } return "upload successful"; } private Boolean isImageFile(String fileName) { String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"}; if (fileName == null) { return false; } fileName = fileName.toLowerCase(); for (String type : img_type) { if (fileName.endsWith(type)) { return true; } } return false; } /** * 獲取檔案字尾名 * * @param fileName * @return */ private String getFileType(String fileName) { if (fileName != null && fileName.indexOf(".") >= 0) { return fileName.substring(fileName.lastIndexOf("."), fileName.length()); } return ""; } }
環境為springboot2.0.6
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
spring.servlet.multipart.resolve-lazily=false