我想上传一些照片到我的服务器,我欺骗了我的朋友代码。但是当我控制台req(
console.log(req)
)时,结果是不同的。如果我编写该代码,结果未定义,我就无法执行console.log(req.file)
,我必须使用req.files.photo
进行更改,但在我朋友的代码中,结果成功,无需更改为req.files.photo
这些是我的路线和multer配置(与我朋友的代码相同):
const multerDiskStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './assets/images/');
},
filename: function(req, file, cb) {
const originalName = file.originalname;
const nameArr = originalName.split('.');
var extension = '';
if(nameArr.length > 1) {
extension = nameArr[nameArr.length - 1];
}
cb(null, file.filename+'-'+Date.now()+'.'+extension);
}
});
const multerUpload = multer({storage: multerDiskStorage});
router.patch('/upload', multerUpload.single('photo'), async function(req, res, next) {
try {
const photo = req.file;
console.log(photo)
const photoPerson = 'http://localhost:3000/api/person/getphoto/'+photo.filename;
console.log('foto', photo);
if(!photo) {
res.status(400).json({'message': 'Picture cannot be empety'});
return
}
} catch (err) {
res.status(400).json({
'status': 'ERROR',
'messages': err.message,
'values': {},
})
}
});
我的代码的结果是:
foto {
photo: {
name: 'apeng 1.jpg',
data: <Buffer ff d8 ff e1 11 21 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 12 01 00 00 03 00 00 00 01 04 1b 00 00 01 01 00 03 00 00 00 01 05 dc 00 00 01 02 00 03 ... 700959 more bytes>,
size: 701009,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/jpeg',
md5: '4e0774cd7159716b00c8e89fe4b8dee4',
mv: [Function: mv]
}
}
我朋友的代码的结果是:
foto {
fieldname: 'photo',
originalname: 'desain.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './assets/images/',
filename: 'undefined-1618923348508.jpeg',
path: 'assets\\images\\undefined-1618923348508.jpeg',
size: 45544
}
检查您的中间件。我认为你使用https://www.npmjs.com/package/express-fileupload。它会在 multer 之前捕获您的照片