简体   繁体   中英

how to convert image dataUrl into [objec file] using jquery or javascript before upload for client side

I am trying to resize the image file using canvasResize() then it convert the file object into dataUrl image size(57x57).I need to upload image with size(57x57) in server. Any idea to converting dataUrl image into file object ([object file]) please help me.

<html>
  <head>
   <script src="jquery.js"></script>
   <script>
   function submit(){ 
     var fileData = $('#Image').get(0).files[0];
     alert(fileData);// look like ([object file]);

     canvasResize(fileData, {
      width: 57,
      height: 57,
      crop: false,
      quality: 80,
      //rotate: 90,
      callback: function(data, width, height) {
        console.log("source: "+data)
      }
     }
   }
   </script>
  </head>
  <body>
     <input type="file" id="Image" onClick="javascript:submit();"/>
  </body>
</html>

First, use draw your image file into the 57x57 canvas, then use the following code convert dataurl to blob and ajax send.

function readFileAsDataURL(blob, callback) {
    var a = new FileReader();
    a.onload = function(e) {callback(e.target.result);};
    a.readAsDataURL(blob);
}
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

var fileObject = $('#Image')[0].files[0];
readFileAsDataURL(fileObject, function (dataurl){
    var canvas = $('<canvas width=57 height=57></canvas>')[0];
    var img = new Image();
    img.onload = function (){
        canvas.drawImage(img,0,0,57,57);
        var dataurl = canvas.toDataURL('image/jpeg',0.8);
        //var dataurl = canvas.toDataURL('image/png');  //if you need png
        var blob = dataURLtoBlob(dataurl);
        var fd = new FormData();
        fd.append("myFile", blob, "thumb.jpg");
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/', true);
        xhr.onload = function(){
            alert('upload complete');
        };
        xhr.send(fd);
    };
    img.src = dataurl;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM