移動端普及的時代,流量是用戶最關心的,手機拍出來的照片基本上都在1~2M以上,這樣上傳會很是耗流量,影響用戶體驗,此例能在保證清晰度的狀況下,將4.5M的圖片壓縮爲30Kjavascript
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>HTML5上傳圖片預覽</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 6 <script src="http://www.codefans.net/ajaxjs/jquery-1.6.2.min.js"></script> 7 <script src="dist/lrz.bundle.js" type="text/javascript"></script> 8 </head> 9 <body> 10 <h3>請選擇圖片文件:JPG/GIF</h3> 11 12 <input type="file" id="payfile" name="myfile" onchange="fileChange(this)" /> 13 14 </form> 15 <script> 16 function fileChange(that){ 17 var path =$("#ctx").val(); 18 var filepath=$(that).val(); 19 if(filepath==""){ 20 return; 21 } 22 var extStart=filepath.lastIndexOf("."); 23 var ext=filepath.substring(extStart,filepath.length).toUpperCase(); 24 if(".jpg|.png|.bmp|.jpeg".toUpperCase().indexOf(ext.toUpperCase())==-1){ 25 alert("只容許上傳jpg、png、bmp、jpeg格式的圖片"); 26 return false; 27 } 28 //以圖片寬度爲800進行壓縮 29 lrz(that.files[0],{ 30 width: 800 31 }) 32 .then(function (rst){ 33 //壓縮後異步上傳 34 $.ajax({ 35 url : "http://192.168.1.168/storage/pages/AnJuKe/up.htm", 36 type: "POST", 37 data : { 38 imgdata:rst.base64//壓縮後的base值 39 }, 40 dataType:"json", 41 cache:false, 42 async:false, 43 success : function(data) { 44 if(data.success){ 45 alert(data.message);///data.message爲上傳成功後的文件路徑 46 }else{ 47 alert(data.message);///data.message爲上傳失敗緣由 48 } 49 }, 50 error:function(){ 51 alert("上傳失敗"); 52 } 53 }); 54 }); 55 } 56 </script> 57 </body> 58 </html>
1 /** 2 * 文件上傳 3 * @throws IOException 4 */ 5 public ModelAndView up(HttpServletRequest request,HttpServletResponse response) throws IOException { 6 String imgdata = request.getParameter("imgdata"); 7 FileOutputStream outputStream=null; 8 try { 9 String basePath = request.getRealPath("/upload"); 10 String imgPath=basePath+"/test1.jpg"; 11 // new一個文件對象用來保存圖片 12 File imageFile = new File(imgPath); 13 // 建立輸出流 14 outputStream = new FileOutputStream(imageFile); 15 // 得到圖片文件流 16 byte[] result = Base64.decodeBase64(imgdata.split(",")[1].getBytes());//解碼 17 for (int i = 0; i < result.length; ++i) { 18 if (result[i] < 0) {// 調整異常數據 19 result[i] += 256; 20 } 21 } 22 outputStream.write(result); 23 } catch (Exception e) { 24 }finally{ 25 outputStream.flush(); 26 outputStream.close(); 27 } 28 return null; 29 }
js下載html
須要jarjava
commons-codec-1.10.jarjquery