我正在尝试使用Express上传图像,但是我面临两个问题,首先,每当我再次上传同一图像时,它都没有被上传,其次,在上传任何单个图像后,一个文件也上传了。这是我的代码。
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
var file = __dirname +"/images" + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err,data) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
答案 0 :(得分:0)
uploads.single("file")
中间件将处理文件上传。您不必专门fs.read
和fs.write
文件。
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
编辑:上面的代码将以十六进制字符串作为文件名的文件上传,没有任何扩展名。
要添加重命名功能,您需要使用diskStorage
。这是从this github issue页获取的代码。
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
现在,您可以使用uploads
变量作为中间件,如上面的代码片段所示。
您可以根据需要编辑filename: function (req, file, cb) { .. }
。现在文件名将是 <16characterhexstring> .ext
答案 1 :(得分:0)
另一种处理方法是不使用中间件,而使用带有以下选项的手动multer:
try {
var storage = multer.diskStorage({
destination: function(request, file, callback) {
//define folder here by fs.mkdirSync(anyDirName);
},
filename: function(req, file, callback) {
callback(null, anyFileName);
},
limits: self.limits
});
var upload = multer({
storage: storage,
fileFilter: function(request, file, callback) {
// here you can filter out what not to upload..
}
}).any();
upload(request, response, callback);
} catch (e) {
}
希望这会有所帮助!