0

请帮助我,面临多重单文件上传的问题 router.post('/file/upload',upload.single('file'), uploadImage); TypeError:无法读取未定义的属性“单个”[在 postRoute.js(api) 中发现错误]

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

-multer网格存储连接与mongodb图集代码:

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
});

带有 api 调用的 image.js 文件:

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);
  }
}

4

1 回答 1

0

TypeError:无法读取未定义的属性“单个”意味着upload不存在。

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

console.log(upload);
...
router.post('/file/upload', upload.single('file'), uploadImage);
于 2021-08-31T15:09:02.503 回答