I have an Express Rest API which will be used by the Android application. One of the use cases is uploading an image to Amazon S3 and then saving some data in MongoDB and then return the result back to the Android device. The API works well when I use it using Postman. But when sending a request from the Android device, the image gets uploaded to S3 but then returns 404.Even the Mongodb entry is not saved. I am fairly new to Node.js and I am not able to figure out the problem. All other API functions work fine and is only failing in this Multipart request. Here is the code:
var express = require('express');
var router = express.Router();
var facialLibrary = require('../models/facialLibrary');
var configS3 = require('../config/secrets.js');
var AWS = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
// Create an S3 client
var s3 = new AWS.S3({
accessKeyId: configS3.s3_accessKeyId,
secretAccessKey: configS3.s3_secretAccessKey
});
var upload = multer({
storage: multerS3({
s3: s3,
bucket: configS3.s3_bucket,
metadata: function (req, file, cb) {
cb(null, {caregiverId: req.body.imageName});
},
key: function (req, file, cb) {
cb(null, req.body.imageName);
},
acl: 'public-read'
})
});
//request sent should have form/multipart header and the file should be under field uploadedFile
router.post('/add', upload.single('uploadedFile'),function(err, req, res, next) {
if(err){
console.log(err.stack);
}
var new_facialLibrary = new facialLibrary({
imageName: req.file.key,
imageDescription: req.body.imageDescription,
imageUrl: req.file.location,
imageMetadata: req.file.metadata
});
new_facialLibrary.save(function(err, new_facialLibrary){
if(err){return next(err);}
res.status(201).json(new_facialLibrary);
});
});
module.exports = router;
via Himanshu Jain
No comments:
Post a Comment