我正在尝试使用Express.js和Multer从HTML表单上传文件。我已经成功将文件保存到所需位置(名为uploads的文件夹中)。
然而,我想在上传时重命名文件,因为默认情况下,Multer会给它一个奇怪的名称,如:
5257ee6b035926ca99923297c224a1bb
这可能是十六进制时间戳之类的东西,但我需要一个更明确的名称,以便稍后调用脚本。
我遵循了这里找到的解释,但它除了上传具有十六进制名称的文件外,什么都没有做。
此外,两个事件onFileUploadStart和onFileUploadComplete似乎从未被触发,因为我在控制台中没有看到任何日志。
我正在使用两个单独的文件作为服务器和路由:
app.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
/**
* 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;
我一直在搜索,但由于我对Node.js和JavaScript还比较陌生,所以无法找出问题所在。
感谢各位的帮助!
destination
can also simply be astring
when a dynamic upload directory isn't needed. e.i.destination: "uploadedImages/"
instead ofdestination: function (...
- Justin Taddei