I just uploaded a formdata image to a server. This server only returns to me the image's content. I tried wrapping it as a Blob, as a File, I tried fileReader... nothing works. I get this:
the last thing I tried was
const img = new Image(response.data);
and then using this function:
const ImageDataToBlob = function(imageData){
let w = imageData.width;
let h = imageData.height;
let canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext("2d");
ctx.putImageData(imageData, 0, 0, w, h); // synchronous
return new Promise((resolve, reject) => {
canvas.toBlob(resolve); // implied image/png format
})
from here https://gist.github.com/Jonarod/77d8e3a15c5c1bb55fa9d057d12f95bd. But it didn't work either, since the function explode when running ctx.putImageData(imageData, 0, 0, w, h);.
How can I turn this into a valid blob object?
Well I don't know how to test this. Maybe if you provide your file/blob.
Anyway, the idea with my solution is to convert the data to dataURL. Maybe it's not the best way but it works for me and that's a start.
var img = document.querySelector(".img");
fetch("https://picsum.photos/200", {}).then(function(response) {
response.arrayBuffer().then(function(arrayBuffer) {
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
var dataUrl = "data:image/jpg;base64," + base64String;
img.src = dataUrl;
})
})
<img class="img" src="" style="width:100px; height: 100px">