Multer将上载的文件添加到req.file或req.files中。我的代码可以在Chrome中正常工作,但是Firefox(68.01)和Edge(44.17763.1.0)中的req.file和req.files均为空。
为什么请求对象不包含Firefox和Edge中的文件?
我的multer配置:
const path = require('path');
const uuidv4 = require('uuid/v4');
const multer = require('multer');
const projectRoot = require('./projectRoot');
// Allowed audio mime types
const audioMimeTypeToExt = {
'audio/wav': '.wav',
'audio/mp3': '.mp3',
};
// Allowed image mime types
const imageMimeTypeToExt = {
'image/jpeg': '.jpg',
'image/png': '.png'
};
// Storage options
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(projectRoot.path, '/public/tracks/'))
},
filename: function (req, file, cb) {
if (file) {
// New file name is uuid + extension (i.e. '10ba038e-48da-487b-96e8-8d3b99b6d18a.mp3')
cb(null, uuidv4() + audioMimeTypeToExt[file.mimetype])
} else {
console.log('File missing.');
}
}
});
// Filter options
const filter = function (req, file, cb) {
if (!(file.mimetype.toLowerCase() in audioMimeTypeToExt)) {
// Reject upload
cb(null, false);
}
// Accept upload
cb(null, true);
};
const uploadMiddleware = (req, res, next) => {
multer(
{
storage: storage,
fileFilter: filter,
limits: {fileSize: 50000000} //50mb
}
).array('tracks', 10)(req, res, function (err) {
if (err && err.code === "LIMIT_FILE_SIZE") {
return res.status(413).send(err.message);
}
next();
});
};
module.exports = {
audioMimeTypeToExt,
imageMimeTypeToExt,
uploadMiddleware: uploadMiddleware,
};
我的路线
const express = require('express');
const router = express.Router();
const sessionMiddleware = require('../middlewares/sessionMiddleware');
const {uploadMiddleware} = require('../config/multerConfig');
const uploadController = require('../controllers/uploadController');
router.post('/',
sessionMiddleware.requiredLogin,
uploadMiddleware,
uploadController.upload_post
);
module.exports = router;
我的控制器
const {processUploads} = require('../utilities/uploadsProcessor');
exports.upload_post = async function (req, res, next) {
if (req.files && req.files.length) { // req.files empty in Firefox and Edge
await processUploads(req);
console.log('Upload successful.');
res.status(200).end();
}
else {
res.status(404).end();
}
};
谢谢
答案 0 :(得分:0)
找出问题所在。 Firefox和Edge在file.mimetype字段中具有不同的值。对于MP3文件,Chrome添加“音频/ mp3”,而Firefox和Edge添加“音频/ mpeg”。因此,我的过滤器正在过滤不包含“ audio / mp3”或“ audio / wav”模仿类型的文件。