I am trying to upload a file to aws s3, I find the error:
TypeError: Can not read property 'element2' of undefined
I have tried to modify the variables, but the error continues, when I change req.file.element2
by req.body.element2
the error stops appearing, but it does not upload the file I want, even though I have tried to fix it it keeps appearing and I definitely do not know what to do, here is the code where my service is running:
const Busboy = require('busboy');
const AWS = require('aws-sdk');
const BUCKET_NAME = 'hipopo-test';
const IAM_USER_KEY = 'ASDASD5ASDDFGDFG6DFG';
const IAM_USER_SECRET = 'y6838348FSD4SF21f31333gR232ER432f3423';
module.exports = (app) => {
app.post('/api/upload', function (req, res, next) {
const element1 = req.body.element1;
var busboy = new Busboy({ headers: req.headers });
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');
});
});
busboy.on('finish', function() {
console.log('Upload finished');
});
const file = req.file.element2;
console.log(file);
function uploadToS3(file) {
let s3bucket = new AWS.S3({
accessKeyId: IAM_USER_KEY,
secretAccessKey: IAM_USER_SECRET,
Bucket: BUCKET_NAME
});
s3bucket.createBucket(function () {
var params = {
Bucket: BUCKET_NAME,
Key: file.name,
Body: file.data
};
s3bucket.upload(params, function (err, data) {
if (err) {
console.log('error in callback');
console.log(err);
}
console.log('success');
console.log(data);
});
});
uploadToS3(file);
};
req.pipe(busboy);
});
}