【问题标题】:Convert dataUrl to blob and submit through ajax将dataUrl转换为blob并通过ajax提交
【发布时间】:2015-03-19 17:38:01
【问题描述】:

我正在使用 imgly 图像裁剪器插件,针对我的应用做了一些修改。它目前将图像转换为dataUrl 并将图像吐出为base64 图像,我可以将其保存为jpeg。我正在努力将here 中的dataURItoBlob 函数改编为我的应用程序,以便将图像发布到 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"));
    });
  });
});

【问题讨论】:

标签: javascript jquery ajax xmlhttprequest data-uri


【解决方案1】:

更新

“假设我将应用程序保持在相同的形式,我正在尝试弄清楚如何将 dataURL 获取到 post 函数中。”

尝试,在第 15 - 103 行 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})
                       )
    );

另见Handling_the_upload_process_for_a_file

【讨论】:

  • 谢谢!我现在已经在解决方案中得到了它,但是试图弄清楚如何在用户点击渲染按钮后将它应用到转换为 blob,而不仅仅是加载图像。它也只需要在用户点击submit 时发布,从这个修改后的小提琴中新附加的提交按钮:jsfiddle.net/mattography/Lgduvce1/6
  • var blob = dataURItoBlob(dataUrl); 似乎返回 undefined ?难以在包含 24804 行的 jsfiddle 中导航。替代方法可能是使用初始Blob 作为src 渲染图像,而不转换为data URI? , 使用 width , height 属性调整渲染图像的大小?
  • 我们在这篇 SO 帖子中处理的小提琴的重要部分只到第 119 行。图像必须在 dataURI 中以进行图像裁剪(其余代码用于)。
  • "图像必须在 dataURI 中才能进行图像裁剪" ? widthheightimg 元素的属性不是“裁剪”图像?,或者,csstransform:scale(n,n)?服务器期望什么数据类型?另见stackoverflow.com/questions/28856729/…stackoverflow.com/questions/28923269/…
  • @Matt 预期的“作物”或scale 比率是多少?是 a) 原始图像,还是 b) “裁剪”图像上传?
猜你喜欢
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2021-09-05
  • 2015-03-06
  • 1970-01-01
  • 2021-07-19
  • 2015-02-19
相关资源
最近更新 更多