使用gridfs multer上传文件

时间:2019-04-19 05:34:45

标签: express mongoose gridfs

我正在关注本教程(https://medium.com/@andreas.lengkeek/a-major-point-of-trouble-for-first-time-developers-is-working-out-how-to-store-and-upload-files-on-2e847e908332

我正在尝试使用multer和gridfs上传文件,但一直出现此错误TypeError:this.db.collection不是函数,我不知道它来自哪里。

    const config = require("../../config/main").mongoURI;
const router = require("express").Router();
const multer = require("multer");
const { mongo, connection } = require("mongoose");
const Grid = require("gridfs-stream");
Grid.mongo = mongo;
var gfs = Grid(config);

// set up connection to db for file storage
const storage = require("multer-gridfs-storage")({
  url: config,
  file: (req, file) => {
    return {
      filename: file.originalname
    };
  }
});
// sets file input to single file
const singleUpload = multer({ storage: storage }).single("file");
// sets file input to single file
router.get("/files/:filename", (req, res) => {
  gfs.files.find({ filename: req.params.filename }).toArray((err, files) => {
    if (!files || files.length === 0) {
      return res.status(404).json({
        message: "Could not find file"
      });
    }
    var readstream = gfs.createReadStream({
      filename: files[0].filename
    });
    res.set("Content-Type", files[0].contentType);
    return readstream.pipe(res);
  });
});
router.get("/files", (req, res) => {
  gfs.files.find({}).toArray((err, files) => {
    if (!files || files.length === 0) {
      return res.status(404).json({
        message: "Could not find files"
      });
    }
    return res.json(files);
  });
});

0 个答案:

没有答案