类型错误:无法读取 multer 网格中未定义的属性'single'



请帮助我,在多个单一文件上传时遇到问题router.post(/文件/上传,upload.single("文件"),uploadImage);类型错误:无法读取未定义的属性"single"[在postRoute.js(api)中发现错误]

router.post('/file/upload', upload.single('file'), uploadImage);
router.get('/file/:filename', getImage);

-multer grid storage connection with mongodb atlas code:

const multer = require("multer");
const {
GridFsStorage
} = require("multer-gridfs-storage");
const storage = new GridFsStorage({
url: `mongodb://xyz:xyz@blogmern-shard-00-00.6az9f.mongodb.net:27017,blogmern-shard-00-01.6az9f.mongodb.net:27017,blogmern-shard-00-02.6az9f.mongodb.net:27017/blogdata?ssl=true&replicaSet=atlas-hqbs1a-shard-0&authSource=admin&retryWrites=true&w=majority`,
options: {
useUnifiedTopology: true,
useNewUrlParser: true
},
file: (request, file) => {
const match = ["image/png", "image/jpg"];
//if images are not in above format
if (match.indexOf(file.memeType) === -1)
//avoid duplicates in img
return `${Date.now()}-blog-${file.originalname}`;
//if img gets matched
return {
bucketName: "photos",
filename: `${Date.now()}-blog-${file.originalname}`,
};
},
});
const upload = multer({
storage
});

image.js文件与API调用:

const grid = require('gridfs-stream');
const mongoose = require('mongoose');
const url = 'http://localhost:8000';
let gfs;
const connect = mongoose.connection;
connect.once('open', () => {
gfs = grid(connect.db, mongoose.mongo);
gfs.collection('fs');
})
exports.uploadImage = (request, response) => {
try {
if (!request.file)
return response.status(404).json("File not found");
const imageURL = `${url}/file/${request.file.filename}`
response.status(200).json(imageURL);
} catch (error) {
response.status(500).json(error);
}
}
exports.getImage = async(request, response) => {
try {
const file = await gfs.files.findOne({
filename: request.params.filename
});
//change file in img
const readStream = gfs.createReadStream(file.filename);
readStream.pipe(response);
} catch (error) {
response.status(500).json('Failed to fetch image', error);
}
}

TypeError: Cannot read property 'single' of undefined暗示upload不存在

在路由器路由注册之前运行console.log(upload);会发生什么,像这样?

console.log(upload);
...
router.post('/file/upload', upload.single('file'), uploadImage);

最新更新