1、application.yml文件配置
1 # 文件大小 MB必須大寫 2 # maxFileSize 是單個文件大小 3 # maxRequestSize是設置總上傳的數據大小 4 spring: 5 servlet: 6 multipart: 7 enabled: true 8 max-file-size: 20MB 9 max-request-size: 20MB
2、application-resources.yml配置(自定義屬性)
1 #文件上傳路徑 2 file: 3 filepath: O:/QMDownload/Hotfix2/
3、后台代碼
(1)FileService.java:
1 package com.sun123.springboot.service; 2 3 import org.springframework.web.multipart.MultipartFile; 4 5 import java.util.Map; 6 7 public interface FileService { 8 9 Map<String,Object> fileUpload(MultipartFile[] file); 10 }
(2)FileServiceImpl.java:
1 package com.sun123.springboot.service.impl; 2 3 4 import com.sun123.springboot.FileUtil; 5 import com.sun123.springboot.service.FileService; 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Value; 10 import org.springframework.stereotype.Service; 11 import org.springframework.web.multipart.MultipartFile; 12 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 import java.io.File; 16 import java.io.FileInputStream; 17 import java.io.PrintWriter; 18 import java.util.*; 19 20 /** 21 * @ClassName FileServiceImpl 22 * @Description TODO 23 * @Date 2019/3/22 22:19 24 * @Version 1.0 25 */ 26 @Service 27 public class FileServiceImpl implements FileService { 28 private static Logger log= LoggerFactory.getLogger(FileServiceImpl.class); 29 30 //文件上傳路徑 @Service包含@Component 31 @Value("${file.filepath}") 32 private String filepath; 33 34 35 Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); 36 //會將上傳信息存入此處,根據需求自行調整 37 List<String> fileName =new ArrayList<String>(); 38 39 //必須注入,不可以創建對象,否則配置文件引用的路徑屬性為null 40 @Autowired 41 FileUtil fileUtil; 42 43 @Override 44 public Map<String, Object> fileUpload(MultipartFile[] file) { 45 46 HttpServletRequest request = null; 47 HttpServletResponse response; 48 49 resultMap.put("status", 400); 50 if(file!=null&&file.length>0){ 51 //組合image名稱,“;隔開” 52 // List<String> fileName =new ArrayList<String>(); 53 PrintWriter out = null; 54 //圖片上傳 55 56 try { 57 for (int i = 0; i < file.length; i++) { 58 if (!file[i].isEmpty()) { 59 //上傳文件,隨機名稱,","分號隔開 60 fileName.add(fileUtil.uploadImage(request, filepath+"upload/"+ fileUtil.formateString(new Date())+"/", file[i], true)+fileUtil.getOrigName()); 61 62 } 63 } 64 //上傳成功 65 if(fileName!=null&&fileName.size()>0){ 66 System.out.println("上傳成功!"); 67 resultMap.put("images",fileName); 68 resultMap.put("status", 200); 69 resultMap.put("message", "上傳成功!"); 70 }else { 71 resultMap.put("status", 500); 72 resultMap.put("message", "上傳失敗!文件格式錯誤!"); 73 } 74 } catch (Exception e) { 75 e.printStackTrace(); 76 resultMap.put("status", 500); 77 resultMap.put("message", "上傳異常!"); 78 } 79 System.out.println("==========filename=========="+fileName); 80 81 }else { 82 resultMap.put("status", 500); 83 resultMap.put("message", "沒有檢測到有效文件!"); 84 } 85 return resultMap; 86 } 87 88 }
(3)FileUtil.java:
1 package com.sun123.springboot; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.stereotype.Component; 5 import org.springframework.web.multipart.MultipartFile; 6 7 import javax.servlet.http.HttpServletRequest; 8 import java.io.File; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 12 /** 13 * Created by wangluming on 2018/5/24. 14 */ 15 @Component 16 public class FileUtil { 17 18 // //文件上傳路徑 19 // @Value("${file.filepath}") 20 // private String filepath; 21 22 //文件隨機名稱 23 private String origName; 24 25 public String getOrigName() { 26 return origName; 27 } 28 29 public void setOrigName(String origName) { 30 this.origName = origName; 31 } 32 33 /** 34 * 35 * @param request 36 * @param path_deposit 新增目錄名 支持多級不存在目錄 37 * @param file 待文件 38 * @param isRandomName 是否要基於圖片名稱重新編排名稱 39 * @return 40 */ 41 public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) { 42 43 44 //上傳 45 try { 46 String[] typeImg={"gif","png","jpg","docx","doc","pdf"}; 47 48 if(file!=null){ 49 origName=file.getOriginalFilename();// 文件原名稱 50 System.out.println("上傳的文件原名稱:"+origName); 51 // 判斷文件類型 52 String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null; 53 if (type!=null) { 54 boolean booIsType=false; 55 for (int i = 0; i < typeImg.length; i++) { 56 if (typeImg[i].equals(type.toLowerCase())) { 57 booIsType=true; 58 } 59 } 60 //類型正確 61 if (booIsType) { 62 //存放圖片文件的路徑 63 //String path="O:\\QMDownload\\Hotfix\\"; 64 //String path=filepath; 65 //System.out.print("文件上傳的路徑"+path); 66 //組合名稱 67 //String fileSrc = path+path_deposit; 68 String fileSrc = path_deposit; 69 //是否隨機名稱 70 if(isRandomName){ 71 //隨機名規則:文件名+_CY+當前日期+8位隨機數+文件后綴名 72 origName=origName.substring(0,origName.lastIndexOf("."))+"_CY"+formateString(new Date())+ 73 MathUtil.getRandom620(8)+origName.substring(origName.lastIndexOf(".")); 74 } 75 System.out.println("隨機文件名:"+origName); 76 //判斷是否存在目錄 77 File targetFile=new File(fileSrc,origName); 78 if(!targetFile.exists()){ 79 targetFile.getParentFile().mkdirs();//創建目錄 80 } 81 82 //上傳 83 file.transferTo(targetFile); 84 //完整路徑 85 System.out.println("完整路徑:"+targetFile.getAbsolutePath()); 86 return fileSrc; 87 } 88 } 89 } 90 return null; 91 }catch (Exception e) { 92 e.printStackTrace(); 93 return null; 94 } 95 } 96 97 /** 98 * 格式化日期並去掉”-“ 99 * @param date 100 * @return 101 */ 102 public String formateString(Date date){ 103 SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd"); 104 String list[] = dateFormater.format(date).split("-"); 105 String result = ""; 106 for (int i=0;i<list.length;i++) { 107 result += list[i]; 108 } 109 return result; 110 } 111 }
(4)MathUtil.java:
1 package com.sun123.springboot; 2 3 import java.security.MessageDigest; 4 import java.util.Random; 5 6 public class MathUtil { 7 /** 8 * 獲取隨機的數值。 9 * @param length 長度 10 * @return 11 */ 12 public static String getRandom620(Integer length){ 13 String result = ""; 14 Random rand = new Random(); 15 int n = 20; 16 if(null != length && length > 0){ 17 n = length; 18 } 19 boolean[] bool = new boolean[n]; 20 int randInt = 0; 21 for(int i = 0; i < length ; i++) { 22 do { 23 randInt = rand.nextInt(n); 24 25 }while(bool[randInt]); 26 27 bool[randInt] = true; 28 result += randInt; 29 } 30 return result; 31 } 32 /** 33 * MD5 加密 34 * @param str 35 * @return 36 * @throws Exception 37 */ 38 public static String getMD5(String str) { 39 MessageDigest messageDigest = null; 40 try { 41 messageDigest = MessageDigest.getInstance("MD5"); 42 messageDigest.reset(); 43 messageDigest.update(str.getBytes("UTF-8")); 44 } catch (Exception e) { 45 //LoggerUtils.fmtError(MathUtil.class,e, "MD5轉換異常!message:%s", e.getMessage()); 46 } 47 48 byte[] byteArray = messageDigest.digest(); 49 StringBuffer md5StrBuff = new StringBuffer(); 50 for (int i = 0; i < byteArray.length; i++) { 51 if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) 52 md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); 53 else 54 md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); 55 } 56 return md5StrBuff.toString(); 57 } 58 }
(5)FileController.java:
1 package com.sun123.springboot.controller; 2 3 import com.sun123.springboot.service.FileService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestParam; 8 import org.springframework.web.bind.annotation.ResponseBody; 9 import org.springframework.web.multipart.MultipartFile; 10 11 import java.util.Map; 12 13 /** 14 * @ClassName FileController 15 * @Description TODO 16 * @Date 2019/3/22 22:21 17 * @Version 1.0 18 */ 19 @Controller 20 @RequestMapping(value = "/upload") 21 public class FileController { 22 23 @Autowired 24 private FileService fileService; 25 26 @RequestMapping(value = "/UpLoadImage") 27 @ResponseBody 28 public Map<String,Object> fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception { 29 Map<String, Object> fileUpload = fileService.fileUpload(file); 30 return fileUpload; 31 } 32 }
4、前台代碼(bootstrap)
1 <div class="container" th:fragment="fileupload"> 2 <input id="uploadfile" type="file" class="file" multiple="multiple" name="file"/> 3 4 </div> 5 6 7 <script> 8 $("#uploadfile").fileinput({ 9 10 language: 'zh', //設置語言 11 12 //uploadUrl: "http://127.0.0.1/testDemo/fileupload/upload.do", //上傳的地址 13 uploadUrl: "/upload/UpLoadImage", //上傳的地址 14 15 allowedFileExtensions: ['jpg', 'gif', 'png', 'docx', 'zip', 'txt'], //接收的文件后綴 16 17 //uploadExtraData:{"id": 1, "fileName":'123.mp3'}, 18 showClose: false,//是否顯示關閉按鈕 19 20 uploadAsync: true, //默認異步上傳 21 22 showUpload: true, //是否顯示上傳按鈕 23 24 //showBrowse: true, //是否顯示瀏覽按鈕 25 26 showRemove: true, //顯示移除按鈕 27 28 showPreview: true, //是否顯示預覽 29 30 showCaption: false, //是否顯示標題 31 32 browseClass: "btn btn-primary", //按鈕樣式 33 34 dropZoneEnabled: true, //是否顯示拖拽區域 35 36 //previewFileType: ['docx'], //預覽文件類型 37 //minImageWidth: 50, //圖片的最小寬度 38 39 //minImageHeight: 50,//圖片的最小高度 40 41 //maxImageWidth: 1000,//圖片的最大寬度 42 43 //maxImageHeight: 1000,//圖片的最大高度 44 45 maxFileSize:0,//單位為kb,如果為0表示不限制文件大小 46 47 //minFileCount: 0, 48 49 maxFileCount: 10, //表示允許同時上傳的最大文件個數 50 51 enctype: 'multipart/form-data', 52 53 validateInitialCount: true, 54 55 previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>", 56 57 msgFilesTooMany: "選擇上傳的文件數量({n}) 超過允許的最大數值{m}!", 58 59 }).on("fileuploaded", function (event, data, previewId, index) { 60 61 62 }); 63 </script>