參考這個:http://www.javashuo.com/article/p-dyiaggqc-e.html javascript
1. 配置MultipartResolverhtml
defaultEncoding="UTF-8" 是請求的編碼格式,默認爲iso-8859-1
maxUploadSize="1048576" 是上傳文件的大小,單位爲字節
uploadTempDir="fileUpload/temp" 爲上傳文件的臨時路徑
java
2.前臺表單數組
1 <form enctype="multipart/form-data" id="J_uploadLocalImgForm" method="post"> 2 <input type="hidden" name="authVenderId"> 3 <input type="file" class="hide" id="J_uploadLocalImgFile" name="multipartFile" multiple=""> 4 </form>
input 標籤上寫上multiple 這個時候就能夠選擇多個文件進行上傳,去掉就不支持多選了app
3. js 控制驗證上傳文件格式 ide
通常的話 可能直接就再js中以什麼結尾來判斷格式,但這樣是不許確的,若是文件的後綴被改掉呢? 若是你對文件格式要求嚴格的話,那最好在後臺作一個比較嚴謹的驗證。post
var urlType = urlStr.substring(urlStr.lastIndexOf(".") + 1, urlStr.length); urlType = urlType.toLowerCase(); if (urlType == "jpg" || urlType == "png" || urlType == "jpeg" || urlType == "gif" || urlType == "bmp") {}
4.java代碼編碼
Controller層
/** * 本地圖片上傳 * @param multipartFile multipartFiles * @return CallbackResult<String> */ @RequestMapping("/multipleUploadWatermarkImg") public @ResponseBody CallbackResult<?> multipleUploadWatermarkImg(@RequestBody MultipartFile[] multipartFile){ return service.multipleUploadWatermarkImg(multipartFile); }
這裏有個地方,MultipartFile 後面加的這個[ ] 表明數組嘛,支持多個文件上傳,若是就是單個文件的話,去掉就能夠了,和前面前臺是對應的url
Service層這裏就不寫了,就是對multipartFile文件進行處理,若是是多個文件就先循環在處理,這裏寫幾個MultipartFile的方法spa
這裏的transferTo 很好用的,直接能夠把文件保存到制定路徑 multipartFile.transferTo(new File(path))
問題是倆個同時存在,其中一個使用時會獲取不到上傳文件,網上有人給出瞭解決方法,不過我沒有去驗證,
http://www.itkeyword.com/doc/8187524065876327482/ServletFileUpload-MultipartResolver-javaSpring
這裏還有一個我遇到的小問題,當上傳文件過大時該怎麼辦?
https://bbs.csdn.net/topics/392015065?locationNum=9&fps=1
這裏有人給了個捕獲異常的方法,可是我以爲有點太麻煩了,若是容許的話不如在前臺進行判斷
uploadLocalImgFile : function(e) { var file = e.target.files[0]; if(file.type == "image/png" || file.type == "image/jpeg" || file.type == "image/jpg" || file.type == "image/gif"){ if(file.size > 1024 * 1024){ swal("上傳圖片的大小不能超過1M","","warning"); return false; } } }