【问题标题】:How to create an image file from a dataURL?如何从 dataURL 创建图像文件?
【发布时间】:2014-08-28 20:31:51
【问题描述】:

我正在尝试将图片上传到 Parse.com,我没有文件,但有 dataURL(因为我调整了图片大小),但需要上传图片文件。

欢迎任何提示。

这里是更多细节的代码:

// First want to resize the image, where the result is a dataURL
var dataURL;
function resizePicture(file) {    // This file is the original image
    var reader = new FileReader();
    reader.onloadend = function() {
        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function() {
            var MAX_WIDTH = 100;
            var MAX_HEIGHT = 150;
            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.createElement('canvas');
            canvas.width = tempW;
            canvas.height = tempH;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0, tempW, tempH);
            dataURL = canvas.toDataURL("image/jpeg"); // How can I convert this dataURL to an image file?
        }
    }
    reader.readAsDataURL(file);
}

// Then,  want to upload the image to Parse.com. 
function savePicture() {
    var name = "productPicture.jpg";
    var parseFile = new Parse.File(name, dataURL); // Here instead of dataURL, I need an image file.
    parseFile.save().then(function() {
            // successful save
        }, function(error) {
            alert("The file either could not be read, or could not be saved to Parse.");
    });
}

【问题讨论】:

    标签: javascript image file-upload parse-platform


    【解决方案1】:

    根据API DocumentationParse.File(name, data, type)

    数据

    文件的数据,如:

    1. 字节值数字数组,或
    2. 类似 { base64: "..." } 的对象,带有 base64 编码的字符串。
    3. 使用文件上传控件选择的文件对象。

    (3) 仅适用于 Firefox 3.6+、Safari 6.0.2+、Chrome 7+ 和 IE 10+。

    理论上这应该可行:

    // get everything after "base64,"
    var base64 = dataURL.split('base64,')[1];
    var parseFile = new Parse.File(name, { base64: base64 });
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 1970-01-01
      • 2011-09-19
      • 2014-06-25
      • 2021-07-12
      • 2011-11-19
      • 2020-07-27
      • 2020-06-25
      • 2017-01-20
      相关资源
      最近更新 更多