2013-10-01 87 views
4

我使用jquery在上傳時調整圖像大小,這很好。但我的問題是我想發送調整大小的圖像,並且我想在輸入文件中設置新圖像的數據,以便在提交時將其發送到服務器。但我不能實現這一目標。每次它發送大文件。這裏是我的代碼:調整圖像大小並將其設置爲輸入文件

<div> 
        <input name="photo" type="file"/>      
        <p><span></span></p> 
        <i></i> 
       </div> 
       <script> 

        $().ready(function() { 


         $("input[name*='photo']").change(function(e) { 
          var file = e.target.files[0]; 

          // RESET 
          $('#area p span').css('width', 0 + "%").html(''); 
          $('#area img, #area canvas').remove(); 


          // CANVAS RESIZING 
          $.canvasResize(file, { 
           width: 300, 
           height: 0, 
           crop: false, 
           quality: 80, 
           //rotate: 90, 
           callback: function(data, width, height) { 

            // SHOW AS AN IMAGE 


            $('<img>').load(function() { 

             $(this).css({ 
              'margin': '10px auto', 
              'width': width, 
              'height': height 
             }).appendTo('#area div'); 

            }).attr('src', data); 

            // here i am trying to assign the resized data to my image from my input file 


            $(this).files[0] = data; 

           } 
          }); 

         }); 
        }); 
       </script> 

       <script src="jqLibrary/jquery.exif.js"></script> 
       <script src="jqLibrary/jquery.canvasResize.js"></script> 
       <script src="jqLibrary/canvasResize.js"></script> 
      </div> 
+0

相關https://stackoverflow.com/q/47515232/584192 –

回答

2

事實上,我得到它使用的FileReader工作,然後將數據傳遞到畫布,然後經由javascritp遠程處理提交,如我所用的force.com platform.Here是代碼的一部分:

function uploadFile() { 
    var file = document.getElementById('attachmentFile').files[0]; 
    if(file != undefined) { 
    if(file.size <= maxFileSize) { 
    attachmentName = file.name; 
var fileReader = new FileReader(); 
fileReader.onloadend = function(e) { 
    var tempImg = new Image(); 
    var dataURL; 
    tempImg.src = this.result; 
    tempImg.onload = function() { 
     var MAX_WIDTH = 400; 
     var MAX_HEIGHT = 300; 
     var tempW = tempImg.width; 
     var tempH = tempImg.height; 
     if (tempW > tempH) { 
      if (tempW > MAX_WIDTH) { 
       tempH *= MAX_WIDTH/tempW; 
       tempW = MAX_WIDTH; 
      } 
     } else { 
     if (tempH > MAX_HEIGHT) { 
      tempW *= MAX_HEIGHT/tempH; 
      tempH = MAX_HEIGHT; 
     } 
    } 
    var canvas = document.getElementById('myCanvas'); 
    canvas.width = tempW; 
    canvas.height = tempH; 
    var ctx = canvas.getContext("2d"); 
      ctx.drawImage(this, 0, 0, tempW, tempH); 
    attachment = canvas.toDataURL("image/jpeg");     
    attachment = attachment.slice(23); 
    positionIndex=0; 
    fileSize = attachment.length; 
      //this is a function to post the data 
    uploadAttachment(null); 
     }    
} 
    fileReader.readAsDataURL(file); 

的重要部分是文件的讀取(readAsDataURL)類型

相關問題