Reputation: 11
Please help me , facing problem in multer single file upload router.post('/file/upload',upload.single('file'), uploadImage); TypeError: Cannot read property 'single' of undefined [error found in 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:[email protected]: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 file with api call:
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);
}
}
Upvotes: 0
Views: 671
Reputation: 1
TypeError: Cannot read property 'single' of undefined implies that upload
does not exist.
What happens when you run console.log(upload);
before that router route registration, like this?
console.log(upload);
...
router.post('/file/upload', upload.single('file'), uploadImage);
Upvotes: 0