我是网络开发的新手。我在页面上有一个多文件上传。文件已成功上传,并将multer上传到我的'public / uploads'文件夹中。
如何使用multer创建的req.files访问我刚刚上传的文件名?结果不是数组,虽然multer docs说多个文件,req.files将包含一个数组。
我觉得我的设置不正确。
这是console.log(req.files)
。正如您所看到的,支持不是以逗号分隔的。
[ { fieldname: 'file',
originalname: 'acschemrev5b00690.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'public/uploads',
filename: '1484769679031-acschemrev5b00690.jpeg',
path: 'public/uploads/1484769679031-acschemrev5b00690.jpeg',
size: 79299 } ]
[ { fieldname: 'file',
originalname: 'acschemrev5b00701.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'public/uploads',
filename: '1484769679047-acschemrev5b00701.jpeg',
path: 'public/uploads/1484769679047-acschemrev5b00701.jpeg',
size: 127608 } ]
[ { fieldname: 'file',
originalname: 'acschemrev5b00703.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'public/uploads',
filename: '1484769679109-acschemrev5b00703.jpeg',
path: 'public/uploads/1484769679109-acschemrev5b00703.jpeg',
size: 117312 } ]
这是我的服务器app.js
文件:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
// var upload = multer({ dest: 'uploads/' });
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
},
filename: function (req, file, cb) {
// cb(null, file.fieldname + '-' + Date.now());
cb(null, Date.now() + "-" + file.originalname);
// cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
// set the view engine to pug
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/', function (req, res) {
res.render('index');
});
// from multer
app.post( '/file-upload', upload.any(), function( req, res, next ) {
// Metadata about the uploaded file can now be found in req.file
res.send(req.files);
// console.log(req.files);
currentFiles = req.files;
console.log(req.files);
app.post('/crop-images')
});
我需要处理刚刚上传的文件。做这个的最好方式是什么?我是否需要创建每个文件名的数组,然后处理每个文件名?如何从req.files中获取他们的名字?
谢谢!
答案 0 :(得分:1)
如果您想从req.files
检索文件名,您可以将其映射到它上面:
var filenames = req.files.map(function(file) {
return file.filename; // or file.originalname
});