html圖片上傳並預覽筆記


一、圖片上傳,原圖無壓縮

  1、用到的js和css(只為美規,可以不用):jasny-bootstrap.css、jasny-bootstrap.js

  2、、html代碼

<div class="row">
  <div class="col-xs-6">
          <div class="form-group">
                <label class="control-label col-sm-4" title="">
                   <span class="required ">*</span> ${text('選擇文件')}:<i class="fa icon-question hide"></i></label>
                <div class="col-sm-8">
                    <div class="fileinput fileinput-new input-group" data-provides="fileinput">
                          <div class="form-control" data-trigger="fileinput"><i class="glyphicon glyphicon-file fileinput-exists"></i> <span class="fileinput-filename"></span></div>
                              <span class="input-group-addon btn btn-white btn-file"><span class="fileinput-new">選擇文件</span><span class="fileinput-exists">更改</span>
                                        <input id="file" name="file" type="file" accept=".xls,.xlsx"></span>
                              <a href="#" class="input-group-addon btn btn-white fileinput-exists" data-dismiss="fileinput">清除</a>
                    </div>
               </div>
         </div>
  </div>
</div>

  3、后台接收代碼

@PostMapping(value = "save")
    @ResponseBody
    public String save(@RequestParam("file") MultipartFile file) {
        try {
            /* 文件流拿到了就隨便保存了 */
        } catch (Exception e) {
            e.printStackTrace();
            return renderResult(Global.FALSE, text("保存文件失敗!"));
        }
        return renderResult(Global.TRUE, text("保存文件成功!"));
    }

 四、圖片壓縮后上傳

1、設置js腳本壓縮

  1 async function pushFrom(){
  2   let file3 = document.getElementById('file').files[0];
  3   if(file3 && '' != file3){
  4     let base64 =  await PromiseCompress(file);
  5     var formData = new FormData(form);
  6     formData.append("base64 ",base64 );
  7     
  8     $.ajax({ 
  9        type:'post',  
 10        url: "/alcms/workermonitor/siAlcWorkerMonitor/everydaymonitorsave", 
 11        processData:false,
 12         contentType:false,
 13        data: formData,  //重點必須為一個變量如:data
 14        success:function(data){      
 15       
 16        },
 17        error:function(e){ 
 20        }
 21     }) 
 25   }
 27 }
 28 
 29 //不對圖片進行壓縮
 30 function directTurnIntoBase64(fileObj,callback) {
 31         var r = new FileReader();
 32         //轉成base64
 33         r.onload = function () {
 34             imgBase64 = r.result;
 35          //   console.log(imgBase64);
 36             callback(imgBase64)
 37         }
 38         r.readAsDataURL(fileObj);//轉成base64格式
 39 }
 40 
 41     /* 異步壓縮圖片 */
 42 async function PromiseCompress(fileObj) {
 43     return new Promise(function (resolve, reject) {
 44         compress(fileObj,function (imgBase64) {
 45                 resolve(imgBase64);
 46         })
 47     })
 48 }
 49 
 50 
 51     //對圖片進行壓縮
 52 function compress(fileObj,callback) {
 53     console.log('准備壓縮的對象:'+fileObj);
 54     if(!fileObj){
 55         console.log('不壓縮');
 56         return;
 57     }
 58     if(typeof (FileReader) === 'undefined'){
 59         console.log("當前瀏覽器內核不支持base64圖片壓縮")
 60         directTurnIntoBase64(fileObj,callback);
 61     }else{
 62         try{var reader = new FileReader();
 63             // 原圖
 64             var yimage = $('<img/>');
 65             yimage.src = fileObj.result;
 66             reader.onload = function (e) {var image = $('<img/>');
 67                 image.on('load',function () {
 68                     let imageNW = this.naturalWidth;
 69                     let imageNH = this.naturalHeight;
 70                     let compressRatia = 1;
 71                     if(imageNH > 800){
 72                         // 圖片高大於800時等比例縮小到800以下
 73                         compressRatia = 800 / imageNH;
 74                     }else if(imageNW > 500){
 75                         // 圖片寬大於500時等比例縮小到500以下
 76                         compressRatia = 500 / imageNW;
 77                     }
 78                     //定義畫布大小,也就是圖片壓縮之后的像素
 79                     var squareW = Number(imageNW * compressRatia).toFixed(0);
 80                     var squareH = Number(imageNH * compressRatia).toFixed(0);
 81                     var canvas = document.createElement('canvas'),
 82                         context = canvas.getContext('2d'),
 83                         imageWidth = 0, //壓縮圖片大小
 84                         imageHeight = 0,
 85                         offsetX = 0,
 86                         offsetY = 0,
 87                         data = '';
 88                         canvas.width = squareW;
 89                         canvas.height = squareH;
 90                         context.clearRect(0,0,squareW,squareH);
 91                     console.log('判斷寬度');
 92                     if(this.width > squareW){
 93                         imageWidth = Math.round(squareW);
 94                         imageHeight = squareH;
 95                         offsetX = Math.round((imageWidth-squareW)/2);
 96                     }else{
 97                         imageHeight = Math.round(squareH);
 98                         imageWidth = squareW;
 99                         offsetY = Math.round((imageHeight - squareH)/2)
100                     }
101                     console.log('准備壓縮');
102                     context.drawImage(this,offsetX,offsetY,imageWidth,imageHeight);
103                     var data = canvas.toDataURL('image/jpeg')
104                     callback(data)
105                 });
106                 image.attr('src',e.target.result)
107             };
108             console.log('執行reader.readAsDataURL');
109             console.log(Object.prototype.toString.call(fileObj));
110             console.dir(fileObj);
111             reader.readAsDataURL(fileObj);
112         }catch (e) {
113             console.log('壓縮失敗!' + e);
114             //調用不壓縮方法
115             directTurnIntoBase64(fileObj,callback)
116         }
117     }
118 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM