Reputation: 235
I am building a proxy that needs to accept a base64 encoded image and pass it as raw bites to another API (that I don't control) using Axios and form-data.
The issue is that if I pass base64 using Axios the call fails to generate a file on the API.
However, if I pass a buffer:
Buffer.from(base64FromRequest)
it generates a file but it is corrupted.
I tested by using a local file:
const testFile= fs.readFileSync(*);
and passing the output to the API and it works. But if I get the testFile and convert it to a base64 buffer and then back to buffer it creates a corrupted file.
const base64FromTestFile = Buffer.from(localFile).toString('base64');
const bufferFromFile = Buffer.from(base64FromTestFile);
I can see that the buffer array for localFile is shorter than the buffer array from bufferFromFile .
Any idea on what may be the issue?
My code:
// Test with local file
const testFile = fs.readFileSync('/iconQA.png');
//Convert testFile to base64 buffer
const base64FromTestFile = Buffer.from(testFile).toString('base64');
// Base64 from request
const base64FromRequest = request['filecontent']['content'];
// True
console.log(base64FromTestFile === base64FromRequest);
const bufferFromFile = Buffer.from(base64FromTestFile);
const bufferRequest = Buffer.from(base64FromRequest);
//Works
const params = new FormData();
params.append('f', 'json');
params.append('token', token);
params.append('attachment', testFile, 'testFile.png');
//Corrupted file
const params = new FormData();
params.append('f', 'json');
params.append('token', token);
params.append('attachment', bufferFromFile, 'bufferFromFile.png');
//Corrupted file
const params = new FormData();
params.append('f', 'json');
params.append('token', token);
params.append('attachment', bufferRequest, 'bufferRequest.png');
Upvotes: 2
Views: 6234
Reputation: 1597
You missed the encoding argument Buffer.from(base64FromTestFile, 'base64')
Upvotes: 4