I am trying to upload an image from Ajax to S3 on AWS lambda function using node JS, but the image is getting corrupted. My Code is as follows.
Client Side:
var formData = new FormData();
formData.append('file', e.target.files[0]);
formData.append('operation', 'uploadImage');
$.ajax({
type: 'post',
url: 'AWS-API-Gateway-URL-here',
processData: false,
contentType: false,
dataType: 'json',
data: formData
}).done(function (response) {
}.bind(this)).always(function () {
});
Lambda Function code below in NodeJS:
const getContentType = event => {
const contentType = event.headers["content-type"];
if (!contentType) {
return event.headers["Content-Type"];
}
return contentType;
};
Parser function:
const parser = (event) => new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
'content-type': getContentType(event)
}
});
const result = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', data => {
result.file = data;
});
file.on('end', () => {
result.filename = filename;
result.contentType = mimetype;
});
});
busboy.on('field', (fieldname, value) => {
result[fieldname] = value;
});
busboy.on('error', error => reject(error));
busboy.on('finish', () => {
event.body = result;
resolve(event);
});
busboy.write(event.body, event.isBase64Encoded ? 'base64' : 'binary');
busboy.end();
});
Image upload Function:
const uploadPropertyImage = (buffer, fileName) =>
new Promise((resolve, reject) => {
const bucketName = "BUCKET-NAME";
var filePath = `${fileName}`;
const data = {
Bucket: bucketName,
Key: filePath,
Body: buffer,
ACL: 'public-read',
};
s3.upload(data, (error, data) => {
if (!error) {
resolve(data.Location);
} else {
reject(new Error("error during put"));
}
});
});
Calling parser function from AWS handler:
parser(event).then(() => {
var request = event.body;
if (request.operation == "uploadImage") {
uploadPropertyImage(request.file, request.filename)
.then((result) => {
// handles succesfull upload
}).catch(() => {
// error
});
}
});
My Image is getting uploaded, but the uploaded image is corrupted. Please help.
I've upped the memory count and it seems to be working.... I'm sure I tried this before but who knows. More as I get it.
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.