将Dropzone文件对象转换为base64字符串

3

我将尝试使用JSON发送Dropzone文件,因此我希望将图像解码为base64。 我尝试了这个函数:

function getBase64Image(imgElem) {
    var canvas = document.createElement("canvas");
    canvas.width = imgElem.clientWidth;
    canvas.height = imgElem.clientHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgElem, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

现在,为了测试base64转换器,我写了这个Dropzone。

$("form#dropzone").dropzone({
    url: allPaths.baseUrl + 'Services/PictureUpload.asmx/HandleFileDropped',
    uploadMultiple: true,
    autoProcessQueue: false,
    acceptedFiles: "image/*",
    init: function() {
        this.on("addedfile", function(file) {
            console.log(getBase64Image(file));
        });
    }    
});

我遇到了一个错误,提示文件对象无效。


你能够复制粘贴你所遇到的确切错误吗?我建议首先使用一些静态图像来测试这个函数。 - barbsan
2个回答

7
我发现文件.DATAURL已经有了base64(不需要上述函数),因此在此发布我的解决方案:
 $("form#dropzone").dropzone({
        url: allPaths.baseUrl + 'Services/PictureUpload.asmx/HandleFileDropped',
        uploadMultiple: true,
        autoProcessQueue: false,
        acceptedFiles: "image/*",
        init: function() {
            this.on("addedfile", function (file) {
                var reader = new FileReader();
                reader.onload = function(event) {
                    // event.target.result contains base64 encoded image
                    var base64String = event.target.result;
                    var fileName = file.name
                    handlePictureDropUpload(base64String ,fileName );
                };
                reader.readAsDataURL(file);

            });
        }

    });

3

因为我是通过Ajax保存到json对象中,所以采用了不同的方法。

首先,我声明了一个全局数组。

images = [];

我这样访问我的放置区文件,并将它们推送到我的图像数组中。

 for (var i = 0; i < $animalImage.files.length; i++) {
            images.push($animalImage.files[i]);
        }

接下来,我将该数组添加到我的JSON对象(动物)中,并将它们与我在模型(ASP.NET C#)中期望的信息进行了映射。

 animal.Pictures = $.map(images, function (img) {
            return {
                base64: img.dataURL.replace(/^data:image\/[a-z]+;base64,/, ""),
                fileName: img.name,
                type: img.type
            };
        });

你可以看到,我映射了从图片中获取的base64信息。

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接