简体   繁体   中英

AWS Lambda base64 encoded form data with image in Node

So, I'm trying to pass an image to a Node Lambda through API Gateway and this is automatically base64 encoded. This is fine, and my form data all comes out correct, except somehow my image is being corrupted, and I'm not sure how to decode this properly to avoid this. Here is the relevant part of my code:

const multipart = require('aws-lambda-multipart-parser');

exports.handler = async (event) => {
    console.log({ event });
    const buff = Buffer.from(event.body, 'base64');
    // using utf-8 appears to lose some of the data
    const decodedEventBody = buff.toString('ascii'); 
    const decodedEvent = { ...event, body: decodedEventBody };
    const jsonEvent = multipart.parse(decodedEvent, false);
    const asset = Buffer.from(jsonEvent.file.content, 'ascii');
}

First off, it would be good to know if aws-sdk had a way of parsing the multipart form data rather than using this unsupported third party code. Next, the value of asset ends with a buffer that's exactly the same size as the original file, but some of the byte values are off. My assumption is that the way this is being encoded vs decoded is slightly different and maybe some of the characters are being interpreted differently.

Just an update in case anybody else runs into a similar problem - updated 'ascii' to 'latin1' in both places and then it started working fine.

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