Convert Data URI to File then append to FormData

后端 未结 14 2597
逝去的感伤
逝去的感伤 2020-11-21 07:14

I\'ve been trying to re-implement an HTML5 image uploader like the one on the Mozilla Hacks site, but that works with WebKit browsers. Part of the task is to extract an imag

14条回答
  •  北海茫月
    2020-11-21 07:26

    Firefox has canvas.toBlob() and canvas.mozGetAsFile() methods.

    But other browsers do not.

    We can get dataurl from canvas and then convert dataurl to blob object.

    Here is my dataURLtoBlob() function. It's very short.

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
    }
    

    Use this function with FormData to handle your canvas or dataurl.

    For example:

    var dataurl = canvas.toDataURL('image/jpeg',0.8);
    var blob = dataURLtoBlob(dataurl);
    var fd = new FormData();
    fd.append("myFile", blob, "thumb.jpg");
    

    Also, you can create a HTMLCanvasElement.prototype.toBlob method for non gecko engine browser.

    if(!HTMLCanvasElement.prototype.toBlob){
        HTMLCanvasElement.prototype.toBlob = function(callback, type, encoderOptions){
            var dataurl = this.toDataURL(type, encoderOptions);
            var bstr = atob(dataurl.split(',')[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            var blob = new Blob([u8arr], {type: type});
            callback.call(this, blob);
        };
    }
    

    Now canvas.toBlob() works for all modern browsers not only Firefox. For example:

    canvas.toBlob(
        function(blob){
            var fd = new FormData();
            fd.append("myFile", blob, "thumb.jpg");
            //continue do something...
        },
        'image/jpeg',
        0.8
    );
    

提交回复
热议问题