I want to send a generated image from a React
frontend to an Express
server but since I can't send a Blob()
object with axios (I get an empty object) my idea was to get the raw image data with Blob().text()
first, send that to the express backend and transform it back to a File()
object there (File()
inherites from Blob()
) but somehow all I get is an blank squared png
which was definetly not what I send.
React
async mint() {
const blob = await htmlToImage.toBlob(document.querySelector('.kryptoweapon'));
const rawPng = await blob.text();
const response = await axios.post('http://localhost:3002/api/mint', {
rawPng,
metadata: this.state
});
}
Express (node)
const { rawPng } = req.body;
const { name, type, blockz, starz } = req.body.metadata;
const nft = {
name,
description: '',
image: new File([rawPng], `blaat.png`, { type: 'image/png' }),
...
}
CodePudding user response:
You can't get image content by using Blob.text. It returns bytes in UTF-8 format, which isn't the right format for images.
Otherwise there are 2 options.
1) Use FormData instead
It's another content type for HTTP requests, you can read her https://developer.mozilla.org/en-US/docs/Web/API/FormData
On client-side
var form = new FormData();
form.append('name', yourblob);
On Node.js it can be handled for example by a very common library
https://www.npmjs.com/package/multer
2) Encode/Decode to Base64
It's a common encode/decode algorithm which can be performed also with files to get a string https://en.wikipedia.org/wiki/Base64
On client-side
function encodeBase64(blob) {
var reader = new FileReader();
reader.onloadend = function() {
var base64Result = reader.result;
}
reader.readAsDataURL(blob);
}
On server-side
You can read her NodeJS: How to decode base64 encoded string back to binary?
After collecting the buffer convert it to file, for example with using
fs.createWriteStream('your/path/to/store/image').write(buffer);
CodePudding user response:
Blob.text() uses UTF-8 encoding which isn't the right format for images, use FileReader.readAsText() instead, which depending on blob's type uses different encoding.
const reader = new FileReader();
reader.addEventListener("load", () => {
const result = reader.result;
//Send this result to Node.js
}, false);
reader.readAsText(yourBlob);