Search code examples
amazon-web-servicesamazon-s3aws-lambdaaws-sdkaws-sdk-nodejs

Uploading a File from a Website to S3


I am trying to upload an image (PNG) from my website to S3.

I am sending a multipart/form-data request to a Lambda, then parsing it using Busboy.

It uploads to S3 fine and shows that it is an image/png but if I download the file and try to view it, the file is invalid

What could cause that? I don't see where I'm going wrong here.

Code:

var AWS = require('aws-sdk');
var BluebirdPromise = require("bluebird");
var Busboy = require('busboy');
var s3 = BluebirdPromise.promisifyAll(new AWS.S3());
var str = require('string-to-stream');

const SavePFP = async((user_id, req) => {
    var busboy = new Busboy({headers: req.headers});

    let res = await(new Promise((resolve) => {
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            console.log('File [' + fieldname + ']: filename: ' + filename);

            file.on('data', function (data) {
                console.log('File [' + fieldname + '] got ' + data.length + ' bytes');

                resolve({
                    filename,
                    encoding,
                    mimetype,
                    data
                });
            });

            file.on('end', function () {
                console.log('File [' + fieldname + '] Finished');
            });
        });

        str(req.rawBody).pipe(busboy);
    }));

    let {data, encoding, mimetype} = res;

    var params = {
        Bucket: '...',
        Key: user_id,
        Body: data,
        ACL: 'public-read',
        ContentEncoding: encoding,
        ContentType: mimetype
    };

    console.log("Uploading to AWS S3...");
    let response = await(s3.upload(params).promise());
    console.log("[SavePFP]: " + JSON.stringify(response, null, 2));

    if (response && response.Location) {
        return response.Location;
    }
});

module.exports = {
    SavePFP
};

Thanks in advance!


Solution

  • I just avoided solving this altogether by converting the file to base64 and uploading it from there.

    Thanks