javascript - 将dataUrl转换为blob并通过ajax提交

标签 javascript jquery ajax xmlhttprequest data-uri

我正在使用 imgly 图像裁剪器插件,该插件针对我的应用程序稍作修改。它当前将图像转换为 dataUrl并将图像输出为 Base64 图像,我可以将其另存为 jpeg。我正在努力调整 dataURItoBlob找到函数here ,到我的应用程序,这样我就可以将图像发布到 API 端点。到目前为止,我有以下内容,但我不确定如何将最终图像附加到 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"));
    });
  });
});

最佳答案

已更新

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

尝试,在 http://jsfiddle.net/mattography/Lgduvce1/6/ 第 15 - 103 行

  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})
                       )
    );

另请参阅Handling_the_upload_process_for_a_file

关于javascript - 将dataUrl转换为blob并通过ajax提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151420/

相关文章:

javascript - 单击按钮直到它在 CasperJS 中消失

javascript - import().Client 类型的参数不可分配给 import().Client 类型的参数

javascript - 传递并返回来自 javascript 和 android 的值,并用作手机间隙插件

javascript - FusionCharts 在 Internet Explorer 中渲染图表需要很长时间(Chrome 更快)

javascript - 涉及 Webgrid 的 Ajax 帮助

javascript - 使用 Ajax 的 Laravel 4 搜索查询

javascript - 使用相同的 npm run 命令动态运行多个 javascript 文件

javascript - 使用 Javascript 和 Jquery 正确的 Img Src 路径

javascript - jQuery ReplaceWith 后查找 div 高度

jquery - ASP.NET + jQuery 上传图片原始尺寸 + 裁剪尺寸