weui上傳多圖片,壓縮,base64編碼的示例代碼
記錄一下在做一個報修功能的心路歷程,需求功能很簡單,一個表單提交,表單包含簡單的文字字段以及圖片
因為使用的是weui框架,前面的話去找weui的表單和圖片上傳組件,說實話,weui的組件寫的還不錯,作為一個不太懂前端的渣渣可以拿來開箱即用
主要是不用調(diào)那么多的樣式問題,直接上代碼:
<div class="weui-cell"> <div class="weui-cell__bd"> <div class="weui-uploader"> <div class="weui-uploader__hd"> <p class="weui-uploader__title">圖片上傳</p> <!-- <div class="weui-uploader__info">0/2</div>--> </div> <div class="weui-uploader__bd"> <ul class="weui-uploader__files" id="uploaderFiles"> <!--<li class="weui-uploader__file" style="background-image:url(/img/upload-btn.png)"></li> <li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(/img/upload-btn.png)"> <div class="weui-uploader__file-content"> <i class="weui-icon-warn"></i> </div> </li> <li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(/img/upload-btn.png)"> <div class="weui-uploader__file-content">50%</div> </li>--> </ul> <div class="weui-uploader__input-box"> <input id="uploaderInput" class="weui-uploader__input zjxfjs_file" type="file" accept="image/*" multiple=""> </div> </div> </div> </div> </div>
//文件上傳js var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>', $gallery = $("#gallery"), $galleryImg = $("#galleryImg"), $uploaderInput = $("#uploaderInput"), $uploaderFiles = $("#uploaderFiles"); $uploaderInput.on("change", function(e) { var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files; //這里獲取到批量的file var fileNum =fileArr.length; for(var i = 0, len = files.length; i < len; ++i) { var file = files[i]; if(fileNum + i + 1 > 5) { break; } // fileArr.push(file); if(url) { src = url.createObjectURL(file); } else { src = e.target.result; } var reader = new FileReader() reader.readAsDataURL(file) reader.onload = function(e) { var image = new Image() //新建一個img標簽(還沒嵌入DOM節(jié)點) image.src = e.target.result image.onload = function () { var canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imageWidth = image.width / 5.5, //壓縮后圖片的大小 imageHeight = image.height / 5.5; canvas.width = imageWidth; canvas.height = imageHeight; context.drawImage(image, 0, 0, imageWidth, imageHeight); var data = { base64: canvas.toDataURL('image/jpeg') } mui.ajax({ url: "/file/uploadBase64", type: "POST", async: false, cache: false, processData: false,// 不處理發(fā)送的數(shù)據(jù) headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(data), success: function(res){ console.log(res) if (res.code==100){ fileArr.push(res.data); //上傳完成,前端頁面顯示 $uploaderFiles.append($(tmpl.replace('#url#', canvas.toDataURL('image/jpeg')))); }else { weui.toast("出錯了,請稍后再試", "forbidden"); } }, error:function () { weui.toast("出錯了,請稍后再試", "forbidden"); } }); } } } checkPhotoSize(); }); //控制顯示5張以內(nèi)照片 function checkPhotoSize(){ if(fileArr.length>4){ $(".weui-uploader__input-box").hide(); }else{ $(".weui-uploader__input-box").show(); } } var index; //第幾張圖片 $uploaderFiles.on("click", "li", function() { index = $(this).index(); $galleryImg.attr("style", this.getAttribute("style")); $gallery.fadeIn(100); }); $gallery.on("click", function() { $gallery.fadeOut(100); }); //刪除圖片 刪除圖片的代碼也貼出來。 $(".weui-gallery__del").click(function() { console.log('刪除'+index); $uploaderFiles.find("li").eq(index).remove(); fileArr.splice(index,1); checkPhotoSize(); });
這里有幾個要注意的點
1、要實現(xiàn)多圖片上傳,對比了幾個UI框架,感覺還是weui的樣式做的最好看
2、考慮到圖片大小問題,一開始我使用的是直接將圖片文件以數(shù)組的形式post給后臺,然后后臺使用MultipartFile 數(shù)組接收,但是這導致有個問題,現(xiàn)在的手機拍照的圖片都比較大,隨便都有個3-5M一張圖片,如果直接post給后臺,用戶體驗不好(速度太慢了),同時也占用了服務(wù)器太多資源(主要是帶寬和存儲空間),所以必須前端先壓縮后再上傳
3、前端壓縮目前能想到的是使用第三方工具接口(阿里或者七牛云端接口);前端頁面利用canvas,進行base64編碼,然后發(fā)送給后端,顯然用后者會比較合適
最后利用canvas將圖片進行base64編碼壓縮,可以實現(xiàn)到將3-5M的圖片圖片壓縮為100k內(nèi),目前實現(xiàn)的是每次上傳圖片都會保存在服務(wù)器上,刪除圖片的話沒法同步刪除服務(wù)器上的圖片,但是這個問題不大,需要修改的話將這個上傳服務(wù)器的請求搞到點擊提交表單的時候再上傳圖片就好了
最后貼一下后端接收代碼:
/** * 上傳圖片信息,base64字符串格式 * @param map * @param model * @return */ @PostMapping(value = "uploadBase64") @ResponseBody public Map<String, Object> uploadBase64Image(@RequestBody Map<String, Object> map) throws ParseException, IOException { Map<String, Object> imageMap = new HashMap<>(); String base64 = map.get("base64").toString(); MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(base64); //獲取文件保存路徑 String fileSavePath = globalConfService.getByKey(StaticConfigUtil.FILE_SAVE_PATH).getConfValue(); String fileServerPath = globalConfService.getByKey(StaticConfigUtil.FILE_SERVER_PATH).getConfValue(); fileSavePath = fileSavePath + DateUtil.formatDatetime("yyyy-MM-dd"); fileServerPath = fileServerPath + DateUtil.formatDatetime("yyyy-MM-dd"); if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String ext=fileName.substring(fileName.lastIndexOf(".")+1); String imgName = "/"+UUID.randomUUID()+ "." +ext; InputStream in = null; OutputStream out = null; try { File serverFile = new File(fileSavePath+imgName); //判斷文件父目錄是否存在 if(!serverFile.getParentFile().exists()){ serverFile.getParentFile().mkdir(); } if (!serverFile.exists()) { serverFile.createNewFile(); } in = file.getInputStream(); out = new FileOutputStream(serverFile); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b))!=-1) { out.write(b, 0, len); } out.close(); in.close(); String serverPath = fileServerPath + imgName; return ResultUtil.successJson(serverPath); } catch (Exception e) { e.printStackTrace(); return ResultUtil.errorJson(ErrorEnum.E_40001,e.getMessage()); } finally { if (out != null) { out.close(); out = null; } if (in != null) { in.close(); in = null; } } } else { return ResultUtil.errorJson(ErrorEnum.E_90007); } } /** * base64轉(zhuǎn)MultipartFile文件 * * @param base64 * @return */ public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStrs = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStrs[1]); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStrs[0]); } catch (IOException e) { e.printStackTrace(); return null; } }
總結(jié)
到此這篇關(guān)于weui上傳多圖片,壓縮,base64編碼的示例代碼的文章就介紹到這了,更多相關(guān)Weui多圖片壓縮上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序購物車、父子組件傳值及calc的注意事項總結(jié)
這篇文章主要給大家介紹了關(guān)于微信小程序購物車、父子組件傳值及calc的注意事項的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-11-11layer實現(xiàn)登錄彈框,登錄成功后關(guān)閉彈框并調(diào)用父窗口的例子
今天小編就為大家分享一篇layer實現(xiàn)登錄彈框,登錄成功后關(guān)閉彈框并調(diào)用父窗口的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09webpack中CommonsChunkPlugin詳細教程(小結(jié))
本篇文章主要介紹了webpack中CommonsChunkPlugin詳細教程(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11JS常見簡單正則表達式驗證功能小結(jié)【手機,地址,企業(yè)稅號,金額,身份證等】
這篇文章主要介紹了JS常見簡單正則表達式驗證功能,結(jié)合實例形式總結(jié)分析了JS針對手機,地址,企業(yè)稅號,金額,身份證等的常見驗證技巧,需要的朋友可以參考下2017-01-01JS 兩日期相減,獲得天數(shù)的小例子(兼容IE,FF)
這篇文章介紹了兩日期相減,獲得天數(shù)的小例子,有需要的朋友可以參考一下2013-07-07