问题
I am using Multer to upload a profile image and unfortunately not working correctly. This is my code:
var express = require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('avatar');
exports.uploadAvatar = function(req, res) {
console.log(req.files);
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
};
and the route:
app.post('/api/uploadAvatar', requiredAuthentication, routes.api.instructor.uploadAvatar);
This is my form:
<form method="post" id="editProfile" enctype="multipart/form-data" action="/api/uploadAvatar">
<div class="form-group">
<label>Profile image <span>*</span></label>
<input type="file" name="avatar" class="form-control" id="avatar" required />
</div>
<div class="form-actions">
<button type="submit" class="button" id="btnSubmit">Upload</button>
</div>
</form>
This is what the console.log(req.files);
is logging:
As you can see, destination is targetting the 'Temp' folder and the filename is not generated. Can someone please find out where things going wrong here?
Please note that I'm using a keystoneJS framework but I beleive it shoudn't make any impact on this.
回答1:
Try this one,
var express = require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('avatar');
module.exports. = { uploadAvatar: upload };
This may works.
回答2:
In my all node API, I have used multer
this way and all time it works fine for me.
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
For more details please look inti this Link.
Hope it may also help you.
来源:https://stackoverflow.com/questions/52206055/nodejs-multer-diskstorage-not-working-why-destination-targeting-temp-folder-an