Created
October 30, 2020 12:51
-
-
Save pedropalhari/68f62cd957b8a87d63a6983fe4e913fa to your computer and use it in GitHub Desktop.
Get blob from <img /> using Canvas. In that way you can append it to a FormData and make a POST with it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//let img = document.querySelector("img"); | |
async function imgSourceToBlob(img) { | |
let canvas = document.createElement('canvas'); | |
canvas.width = img.width; | |
canvas.height = img.height; | |
let ctx = canvas.getContext('2d'); | |
ctx.drawImage(img, 0, 0); | |
let imageBlob = await new Promise((resolve) => { | |
canvas.toBlob((blob) => resolve(blob)); | |
}); | |
return imageBlob; | |
} | |
/** | |
* let body = new FormData(); | |
* let blob = await imgSourceToBlob(img); | |
* body.append( | |
* 'file', | |
* new File([blob], `${Date.now()}_${user._id}_${index}`, { | |
* type: blob.type, | |
* }); | |
* ... | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment