Convert Data URI to File then append to FormData

后端 未结 14 2599
逝去的感伤
逝去的感伤 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:40

    Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer

    function dataURItoBlob(dataURI) {
        'use strict'
        var byteString, 
            mimestring 
    
        if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
            byteString = atob(dataURI.split(',')[1])
        } else {
            byteString = decodeURI(dataURI.split(',')[1])
        }
    
        mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
    
        var content = new Array();
        for (var i = 0; i < byteString.length; i++) {
            content[i] = byteString.charCodeAt(i)
        }
    
        return new Blob([new Uint8Array(content)], {type: mimestring});
    }
    
    0 讨论(0)
  • 2020-11-21 07:43

    Thanks! @steovi for this solution.

    I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).

    converterDataURItoBlob(dataURI) {
        let byteString;
        let mimeString;
        let ia;
    
        if (dataURI.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(dataURI.split(',')[1]);
        } else {
          byteString = encodeURI(dataURI.split(',')[1]);
        }
        // separate out the mime component
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    
        // write the bytes of the string to a typed array
        ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ia], {type:mimeString});
    }
    
    0 讨论(0)
提交回复
热议问题