Javascript 使用 Multer 重命名上传的文件不起作用 (Express.js)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32184589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Renaming an uploaded file using Multer doesn't work (Express.js)
提问by Vincent Montalieu
I'm trying to upload a file from a HTML form using Express.js and Multer. I've managed to save the file to the desired location (a folder named uploads).
我正在尝试使用 Express.js 和 Multer 从 HTML 表单上传文件。我已设法将文件保存到所需位置(名为uploads的文件夹)。
However, I'd like to rename the file while uploading it because, by default, Multer gives it a strange name such as:
但是,我想在上传文件时重命名文件,因为默认情况下,Multer 给它起了一个奇怪的名字,例如:
5257ee6b035926ca99923297c224a1bb
5257ee6b035926ca99923297c224a1bb
Might be a hexadecimal time stamp or so but I need a more explicit name in order to call a script on it later.
可能是一个十六进制时间戳左右,但我需要一个更明确的名称,以便稍后在其上调用脚本。
I've followed the explanation found herebut it doesn't do anything more than it used to: uploading the file with the hexa name.
我已经按照此处找到的解释进行操作,但它并没有做任何比以前更多的事情:上传带有 hexa 名称的文件。
Also, the two events onFileUploadStartand onFileUploadCompletenever seem to be triggered as I don't get anything logged in my console.
此外,onFileUploadStart和onFileUploadComplete这两个事件似乎从未被触发,因为我的控制台中没有记录任何内容。
I am using two separate files for the server and the routing:
我为服务器和路由使用了两个单独的文件:
app.js
应用程序.js
/**
* Dependencies
*/
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
/**
* Importation of routes
*/
var routes = require('./routes/index');
var recog = require('./routes/recog');
/**
* Express
*/
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// pour contrer les erreurs de cross domain
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
/**
* Routes
*/
app.use('/', routes);
app.use('/recog', recog);
module.exports = app;
recog.js
识别.js
/**
* Requirements
*/
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({
dest: 'uploads/',
rename: function (fieldname, filename) {
console.log("Rename...");
return filename + Date.now();
},
onFileUploadStart: function () {
console.log("Upload is starting...");
},
onFileUploadComplete: function () {
console.log("File uploaded");
}
});
/**
* Upload d'une image
*/
router.post('/upload', uploads.single('image'), function (req, res, next) {
console.log("Front-end is calling");
res.json({status: 'success', data: 'Fichier chargé.\nOrgane sélectionné : ' + req.body.organ});
});
module.exports = router;
I have been digging around but I can't figure out what the problem is as I am quite new to Node.js and JavaScript in general.
我一直在挖掘,但我无法弄清楚问题是什么,因为我对 Node.js 和 JavaScript 总体上还是很陌生。
Thanks for your help guys!
谢谢你们的帮助!
回答by Gaurav Gupta
The usage for Multer has changed.
Multer 的用法已经改变。
Currently Multer constructor accepts only three options:
目前 Multer 构造函数只接受三个选项:
- dist/storage
- fileFilter
- limits
- 分发/存储
- 文件过滤器
- 限制
now rename, onFileUploadStart, onFileUploadComplete would not work.
现在重命名,onFileUploadStart,onFileUploadComplete 将不起作用。
however renaming can be done using DiskStorage
但是可以使用 DiskStorage 进行重命名
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
have a look at these links:
看看这些链接:
回答by Thomas Thai
I know this post is dated. I want to contribute to those who may arrive later. Below is a full functional server script to handle multiple uploaded pictures with random saved pictures names and file extension.
我知道这篇文章已经过时了。我想为那些可能迟到的人做出贡献。下面是一个功能齐全的服务器脚本,用于处理随机保存的图片名称和文件扩展名的多张上传图片。
var express = require("express");
var multer = require("multer");
var app = express();
var path = require("path");
var uuid = require("uuid");
// Allow cross origin resource sharing (CORS) within our application
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploadedimages/')
},
filename: function (req, file, cb) {
cb(null, uuid.v4() + path.extname(file.originalname));
}
})
var upload = multer({ storage: storage })
// "files" should be the same name as what's coming from the field name on the client side.
app.post("/upload", upload.array("files", 12), function(req, res) {
res.send(req.files);
console.log("files = ", req.files);
});
var server = app.listen(3000, function() {
console.log("Listening on port %s...", server.address().port);
});
回答by VISHNU Radhakrishnan
we give a random name to file with the help of date and appends the original file extension with help of file.mimetype
我们在日期的帮助下给文件一个随机名称,并在帮助下附加原始文件扩展名 file.mimetype
try console.log(file.mimetype) you will get the file name and extension separated by '/' then I split it to array and fetch the extension from it. Try the below code.
试试 console.log(file.mimetype) 你会得到文件名和扩展名用'/'分隔,然后我把它拆分成数组并从中获取扩展名。试试下面的代码。
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now()+ '.' +extension)
}
})
const upload = multer({ storage: storage })
回答by Pradeep Saini
try this way which i'm using
试试我正在使用的这种方式
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
console.log(file);
var fileObj = {
"image/png": ".png",
"image/jpeg": ".jpeg",
"image/jpg": ".jpg"
};
if (fileObj[file.mimetype] == undefined) {
cb(new Error("file format not valid"));
} else {
cb(null, file.fieldname + '-' + Date.now() + fileObj[file.mimetype])
}
}
})
var upload = multer({ storage: storage })
回答by user2517028
Personally I implemented the following solutions, which generates a random name for files and appends the original file extension (I assume that my extension is after the last . )
我个人实现了以下解决方案,它为文件生成一个随机名称并附加原始文件扩展名(我假设我的扩展名在最后一个 . 之后)
var path = require('path');
var options = multer.diskStorage({ destination : 'uploads/' ,
filename: function (req, file, cb) {
cb(null, (Math.random().toString(36)+'00000000000000000').slice(2, 10) + Date.now() + path.extname(file.originalname));
}
});
var upload= multer({ storage: options });
router.post('/cards', upload.fields([{ name: 'file1', maxCount: 1 }, { name: 'file2', maxCount: 1 }]), function(req, res, next) {
/*
handle files here
req.files['file1']; //First File
req.files['file2']; //Second File
req.body.fieldNames;//Other Fields in the form
*/
});
In the MULTER
documentation you'll find this:
在MULTER
文档中,您会发现:
The disk storage engine gives you full control on storing files to disk.
磁盘存储引擎使您可以完全控制将文件存储到磁盘。
There are two options available, destinationand filename. They are both functions that determine where the file should be stored.
有两个选项可用,destination和filename。它们都是确定文件应该存储在哪里的函数。
Note:You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
Note:Multer will not append any file extension for you, your function should return a filename complete with an file extension.
注意:将目标作为函数提供时,您负责创建目录。传递字符串时,multer 将确保为您创建目录。
文件名用于确定文件夹内文件的名称。如果没有给出文件名,每个文件将被赋予一个不包含任何文件扩展名的随机名称。
注意:Multer 不会为您附加任何文件扩展名,您的函数应该返回一个完整的文件名和文件扩展名。
回答by runha
File has structure like this:
文件具有如下结构:
{
"fieldname": "avatar",
"originalname": "somefile.pdf",
"encoding": "7bit",
"mimetype": "application/pdf",
"destination": "./uploads",
"filename": "36db44e11b83f4513188f649ff445a2f",
"path": "uploads\36db44e11b83f4513188f649ff445a2f",
"size": 1277191
}
}
The next example saves file with it's original name an extension and not with the strange name like it is by default. (Instead of "file.originalname" you can save it as you want)
下一个示例使用它的原始名称和扩展名保存文件,而不是像默认情况下那样使用奇怪的名称。(您可以根据需要保存而不是“file.originalname”)
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads') //Destination folder
},
filename: function (req, file, cb) {
cb(null, file.originalname) //File name after saving
}
})
var upload = multer({ storage: storage })