GridFS 图片上传,无法从数据库中获取文件

问题描述 投票:0回答:0

我正在使用 GridFsStorage 和 mongoose 在 MongoDB 中上传图像文件。 现在我设法完美地上传了图片,我在数据库中检查了它是否存在,现在我想检索它并显示但不知道为什么它不起作用只在控制台中加载没有错误

附上我的 git repo 以检查link

let gfs;
conn.once("open", () => {
  // init stream
  gfs = new mongoose.mongo.GridFSBucket(conn.db, {
    bucketName: "uploads",
  });
});

// Storage
const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename =
          buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "uploads",
        };
        resolve(fileInfo);
      });
    });
  },
});

const upload = multer({
  storage,
});
router.post("/upload", upload.single("file"), (req, res) => {
    res.json({file : req.file});
  });

router.get("/files", (req, res) => {
    gfs.find().toArray((err, files) => {
      // check if files
      if (!files || files.length === 0) {
        return res.status(404).json({
          err: "no files exist"
        });
      }
  
      return res.status(200).json(files);
    });
  });

再次附上我的 git repo 以检查link

node.js mongodb express mongoose gridfs
© www.soinside.com 2019 - 2024. All rights reserved.