简体   繁体   中英

Angular 8, upload (using post multipart/form-data) the result of FileReader.readAsDataURL

My use case:

  1. A user opens an image file (using input type="file" ).
  2. The image is then displayed on screen, and stored in the local storage
  3. At some later point (days) the user clicks a button, and the image should be uploaded to the server, via API based on a POST using multipart/form-data .

I have found examples of both uploading ( example 1 , example 2 ) and previewing. There is one example showcasing both .

My problem is, all of the examples fill the FormData with the File, not the base-encoded URL. If previewing and POSTing are separated in time, it seems redundant to store both in the local storage.

So my question is - how to convert the encoded data URL to the format acceptible to FormData. Intuitively is should be trivial, since POST should encode the binary probably the same way it does in the URL. Is there a standard practice for doing so?

Additional questions that are relevant:

  1. how to upload image in base64 on server
  2. Converting base64 to blob in javascript

Ok, here is what worked for me. Note the code is copied from other SO posts mentioned in the question.

private b64toArrayBuffer(dataURI) {
const byteString = atob(dataURI.split(',')[1]);
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
}
return ia;
}


private b64toBlob(dataURI, mimetype) {
    return new Blob([this.b64toArrayBuffer(dataURI)], {
        type: mimetype
    });
}

const blob = this.b64toBlob(media.url, media.mimetype);
formData.append('file', blob);
return this.http.post(uploadUrl, formData,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM