Convert dataUrl to blob and submit through ajax

这一生的挚爱 提交于 2019-12-11 13:38:34

问题


I'm using the imgly image cropper plugin, slightly modified for my app. It currently converts an image to a dataUrland spits out the image as a base64 image that I can save as a jpeg. I'm working on adapting the dataURItoBlob function found here, to my app, so I can get the image posted to an API endpoint. I have the following so far, but I'm not sure how to append the final image to the xhr.open('POST', '/', true);

renderButton.click(function (event) {
var dataUrl = 

imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {

        //Convert DataURL to Blob to send over Ajax
        function dataURItoBlob(dataUrl) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
        var byteString = atob(dataUrl.split(',')[1]);

        // separate out the mime component
        var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to an ArrayBuffer
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        // write the ArrayBuffer to a blob, and you're done
        //var bb = new BlobBuilder();
        //bb.append(ab);
        //return bb.getBlob(mimeString);
    }


    var blob = dataURItoBlob(dataUrl);
    var fd = new FormData(document.forms[0]);
    var xhr = new XMLHttpRequest();

    fd.append("myFile", blob);
    xhr.open('POST', '/', true);
    xhr.send(fd);



//Appends generated dataUrl to a div 
var image = $("<img><br>").attr({
        src: dataUrl
      });
//Remove button
      image.appendTo($(".result"))
      $button = $('<button class="btn btn-default remove">')
            .text('Remove Image')
            .on('click', function () {
                image.remove();
                $(this).remove();
                return false;
            });
        $button.appendTo($(".result"));
    });
  });
});

回答1:


Updated

"Assuming I keep the app in the same form, I'm trying to figure out how to get the dataURL into the post function."

Try, at lines 15 - 103 at http://jsfiddle.net/mattography/Lgduvce1/6/

  var blob; // declare `blob`
  // As soon as the user selects a file...
  fileInput.addEventListener("change", function (event) {
    var file; // declare `file`    
    var fileToBlob = event.target.files[0];
          blob = new Blob([fileToBlob], {"type":fileToBlob.type});
          // do stuff with blob
          console.log(blob);
    // Find the selected file
    if(event.target.files) {
      file = event.target.files[0];
    } else {
      file = event.target.value;
    }

    // Use FileReader to turn the selected
    // file into a data url. ImglyKit needs
    // a data url or an image
    var reader = new FileReader();
    reader.onload = (function(file) {
      return function (e) {
        data = e.target.result;

        // Run ImglyKit with the selected file
        try {
          imgly.run(data);
        } catch (e) {
          if(e.name == "NoSupportError") {
            alert("Your browser does not support canvas.");
          } else if(e.name == "InvalidError") {
            alert("The given file is not an image");
          }
        }
      };
    })(file);
    reader.readAsDataURL(file);
  });

  // As soon as the user clicks the render button...
  // Listen for "Render final image" click
  renderButton.click(function (event) {
    var dataUrl;


    imgly.renderToDataURL("image/jpeg", { size: "1200" }
    , function (err, dataUrl) {
        // `dataUrl` now contains a resized rendered image with
        // a width of 300 pixels while keeping the ratio

        // Convert DataURL to Blob to send over Ajax
        // function dataURItoBlob(dataUrl) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs 
        // - see SO answer #6850276 for code that does this
        // var byteString = atob(dataUrl.split(',')[1]);

        // separate out the mime component
        // var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to an ArrayBuffer
        // var ab = new ArrayBuffer(byteString.length);
        // var ia = new Uint8Array(ab);
        // for (var i = 0; i < byteString.length; i++) {
        //    ia[i] = byteString.charCodeAt(i);
        // }
        // write the ArrayBuffer to a blob, and you're done
        // var bb = new BlobBuilder();
        // bb.append(ab);
        // return bb.getBlob(mimeString);
    // }


    var _data = dataUrl.split(/,/)[1];
    // var fd = new FormData(document.forms[0]);
    var xhr = new XMLHttpRequest();
        function success(response) {
            if (response.target.readyState === 4) {
                var data = JSON.parse(response.target.response);
                var image = "data:" + data.type + ";base64," + data.file;
                console.log(image); // `data URI` of resized image
            }
        }
        xhr.onload = success;
    // fd.append("myFile", blob);
    xhr.open("POST", "/echo/json/", true);
    xhr.send("json=" + encodeURIComponent(
                           JSON.stringify({"file": _data,"type":blob.type})
                       )
    );

See also Handling_the_upload_process_for_a_file



来源:https://stackoverflow.com/questions/29151420/convert-dataurl-to-blob-and-submit-through-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!