我有一个使用 Multer 用 NodeJS 编写的简单上传应用程序,效果很好。这是代码:
var express = require('express'),
bodyParser = require('body-parser'),
qs = require('querystring'),
multer = require('multer'),
logger = require('morgan');
var config = require('./config'),
oauth = require('./oauth');
function extractExtension(filename) {
return filename.split('.').pop();
}
function getRandom(min, max) {
return Math.floor(Math.random() * max) + min;
}
var app = express();
//app.use(cors());
// Add headers
app.use(function(req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Authorization,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();
});
// Multer
var momentUpload = multer({
dest: './uploads/',
limits: {
fileSize: 256 * 1024 * 1024
},
rename: function(fieldname, filename) {
return Date.now() + '-' + getRandom(100000, 999999) + '.' + extractExtension(filename);
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
}
}).single('file');
app.set('port', 4000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/file/upload', [oauth.ensureAuthenticated, momentUpload, function(req, res) {
console.log(req.body); // form fields
console.log(req.file); // form files
res.status(204).end();
}]);
// Start the Server
app.listen(app.get('port'), function() {
console.log('Metadata store env: ' + config.METADATASTORE_ENV);
console.log('Express server listening on port ' + app.get('port'));
firebase.authenticate();
console.log('Connected to Firebase');
});
然而,问题是 Multer 的配置似乎根本不起作用。destPath 有效,文件出现在我提供的文件夹 (./uploads/) 中。允许更大的文件大小(例如 400MB 的文件,而选项明确指出 256MB),并且回调函数不会被触发一次。没有错误信息。知道我在这里做错了什么吗?我按照 Google 和官方页面上的指南进行操作,但无法正常工作。