无法保存从邮递员发送到multer的图像

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

/**

  • 使用邮递员上传单个文件。 */

我正在尝试上传图片以发布 API,但我没有收到任何回复。因为 upload.single('file'),存储函数被调用了

//常量存储 = new GridFsStorage({ }) 这一行,诺言也渐渐解决了。但它没有回来。到 Post API。

在底部我附上了我邮递员的截图。

//npm run dev
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import multer from "multer";
import { GridFsStorage } from "multer-gridfs-storage";
// const GridFsStorage = require("multer-gridfs-storage").GridFsStorage;
import Grid from "gridfs-stream";
import bodyParser from "body-parser";
import path from "path";
import Pusher from "pusher";

Grid.mongo = mongoose.mongo;

//app config
const app = express();
const port = process.env.PORT || 9000;

//middlewares
app.use(bodyParser.json()); //converts everything to JSON.
app.use(cors());

//db config
const MongoURL =
  "mongodb+srv://fbclient:[email protected]/facebook-db?retryWrites=true&w=majority";

const conn = mongoose.createConnection(MongoURL, {
  //   useFindAndModify: false,
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let gfs;
conn.once("open", () => {
  console.log("DB connected");
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection("images");
});

const storage = new GridFsStorage({
  url: MongoURL,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      const filename = `image-${Date.now()}${path.extname(file.originalname)}`;
      const fileInfo = {
        filename: filename,
        bucketName: "images",
      };
      resolve(fileInfo);
    });
  },
});

const upload = multer({ storage });

mongoose.connect(MongoURL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

//api requests
app.get("/", (req, res) => {
  res.status(200).send("hello world");
});

app.post("/upload/image", upload.single("file"), (req, res) => {
  res.status(201).send(req.file);
});

//listen
app.listen(port, () => console.log(`listening to port ${port}`));


我必须得到我发送的图片的回复

enter image description here

我的 API 没有收到请求吗?或者有没有我没有导入的包?请让我知道

multer multer-gridfs-storage
© www.soinside.com 2019 - 2024. All rights reserved.