我使用以下内容通过Multer将文件上传到目录。它工作得很好,但我需要在上传后执行一些操作,这些操作需要我刚刚发布到“upload”目录的文件名。如何获取刚刚发布的文件的名称?
// Multer storage options
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'upload/');
},
filename: function(req, file, cb) {
cb(null, file.originalname + '-' + Date.now() + '.pdf');
}
});
var upload = multer({ storage: storage });
app.post('/multer', upload.single('file'), function(req, res) {
// Need full filename created here
});
答案 0 :(得分:15)
request.file
提供以下统计信息,您只需选择request.file.originalname
或request.file.filename
即可获取nodejs app创建的新文件名。
{
fieldname: 'songUpload',
originalname: '04. Stairway To Heaven - Led Zeppelin.mp3',
encoding: '7bit',
mimetype: 'audio/mp3',
destination: './uploads',
filename: 'songUpload-1476677312011',
path: 'uploads/songUpload-1476677312011',
size: 14058414
}
例如,在nodejs中用ecma-6表达mvc app,
var Express = require('express');
var app = Express();
var multipartUpload = Multer({storage: Multer.diskStorage({
destination: function (req, file, callback) { callback(null, './uploads');},
filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now());}})
}).single('songUpload');
app.post('/artists', multipartUpload, (req, resp) => {
val originalFileName = req.file.originalname
console.log(originalFileName)
}
答案 1 :(得分:12)
var express=require("express");
var app=express();
var multer=require("multer");
var upload=multer({dest:"uploads/"});
app.post("/multer", upload.single("file"), function(req,res){
console.log(req.file.filename);
});
答案 2 :(得分:5)
访问上传的文件数据在Multer中有所不同,具体取决于您是上传单个还是多个文件。访问数据如下:
上传单个文件:
req.file
上传多个文件:
req.files
答案 3 :(得分:2)
我在github上找到了答案,您可以在中访问它
res.req.file.filename
在此处查看更多信息,https://github.com/expressjs/multer/issues/302
答案 4 :(得分:1)
request.file.filename
fieldname以表格形式指定的字段名称
originalname用户计算机上文件的名称
编码文件的编码类型
mimetype文件类型的Mime类型
size文件大小(以字节为单位)
答案 5 :(得分:1)
app.post('/multer', upload.single('file'), function(req, res) {
// Need full filename created here
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file) #Here
});
您需要从此行恢复文件
res.send(file)
使用file.filename 此输出示例
{
"fieldname": "myFile",
"originalname": "isc te esta esperando.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "uploads",
"filename": "myFile-1602293858948.eaf",
"path": "uploads/myFile-1602293858948.eaf",
"size": 297720
}