Convert Data URI to File then append to FormData

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

    Here is an ES6 version of Stoive's answer:

    export class ImageDataConverter {
      constructor(dataURI) {
        this.dataURI = dataURI;
      }
    
      getByteString() {
        let byteString;
        if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(this.dataURI.split(',')[1]);
        } else {
          byteString = decodeURI(this.dataURI.split(',')[1]);
        }
        return byteString;
      }
    
      getMimeString() {
        return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
      }
    
      convertToTypedArray() {
        let byteString = this.getByteString();
        let ia = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }
        return ia;
      }
    
      dataURItoBlob() {
        let mimeString = this.getMimeString();
        let intArray = this.convertToTypedArray();
        return new Blob([intArray], {type: mimeString});
      }
    }
    

    Usage:

    const dataURL = canvas.toDataURL('image/jpeg', 0.5);
    const blob = new ImageDataConverter(dataURL).dataURItoBlob();
    let fd = new FormData(document.forms[0]);
    fd.append("canvasImage", blob);
    

提交回复
热议问题