I tried to upload image file from client side to my AWS S3 storage server using multer with the support of multer-s3. However, I keep getting undefined result for my req.file call. I have been googling and check all possible causes to my problem and no luck so far. Hope someone can help me here. Thanks in advance.
Client side HTML code:
<form method="post" enctype="multipart/form-data" action="/create">
<input type="text" name="name" />
<input type="text" name="topic" />
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
Server side code:
var express = require('express');
var http = require('http');
var app = express();
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var multer = require('multer');
var multerS3 = require('multer-s3');
var AWS = require('aws-sdk');
app.use(methodOverride());
app.use(bodyParser.urlencoded({ extended: true }));
//Create S3 client
var s3 = new AWS.S3();
//this code is copy directly from multer-s3 since I don't care about my file name shown on S3 for now
var upload = multer({
storage: multerS3({
s3: s3,
bucket: mybuckname,
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
});
app.post('/create', upload.single('image'), function(req, res) {
var nameField = req.body.name,
topicField = req.body.topic;
console.log("File: ", req.file);
console.log("Name: ", nameField);
console.log("Topic: ", topicField);
res.sendStatus(200);
res.end();
});
I have tried the following:
- Removed 'body-parser' and use 'multer' only, then even worse result (both req.body and req.file are undefined). With body-parser, at least I can guarantee req.body is working
- To simplify the cause, I removed all my text field inputs from client side and leave only file upload option to make sure I am only transmitting file data, still return undefined for req.file (multer is not working at all)
- I also read about the possibility that "Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server." In my case, I am not getting the file so it doesn't matter for me now.
- Use multer only without multer-s3, and tried upload.array instead of upload.single, still no luck (multer-s3 is built on top of multer, so I don't think it has anything to do with my current problem, but just to give it a try)
- Skip AWS S3 and store it in local path, still undefined result