簡體   English   中英

Nodejs、MongoDB 用multer上傳圖片

[英]Nodejs, MongoDB upload image with multer

我正在創建和更新配置文件路由,我可以創建和更新配置文件詳細信息,但我無法將圖像保存到我的數據庫中。 我如何將圖像 url 保存到我的數據庫?

個人資料模型,頭像為圖片:

const ProfileSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  location: {
    type: String
  },
  occupation: { type: String },
  bio: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  },
  avatar: { type: String }
});

多路設置:

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./uploads/");
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname);
  }
});
const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/jpeg" ||
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 2
  },
  fileFilter: fileFilter
});

配置文件路徑,我如何將文件路徑存儲到我的數據庫

router.post("/", auth, upload.single("avatar"), async (req, res) => {
  console.log(req.file);

  const { location, occupation, bio } = req.body;
  const { avatar } = req.file.path;
  //Build profile object
  const profileFields = {};
  if (location) profileFields.location = location;
  if (occupation) profileFields.occupation = occupation;
  if (bio) profileFields.bio = bio;

  try {
    // Using upsert option (creates new doc if no match is found):
    let profile = await Profile.findOneAndUpdate(
      { user: req.user.id },

      { $set: profileFields },
      { new: true, upsert: true }
    );
    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

你需要像這樣設置你的頭像:

  if (req.file.path) profileFields.avatar = req.file.path;

所以所有的代碼必須是這樣的:

router.post("/", auth, upload.single("avatar"), async (req, res) => {
  console.log(req.file.path);

  const { location, occupation, bio } = req.body;
  //const { avatar } = req.file.path;
  //Build profile object
  const profileFields = {};
  if (location) profileFields.location = location;
  if (occupation) profileFields.occupation = occupation;
  if (bio) profileFields.bio = bio;
  if (req.file.path) profileFields.avatar = req.file.path;

  try {
    // Using upsert option (creates new doc if no match is found):
    let profile = await Profile.findOneAndUpdate(
      { user: req.user.id },

      { $set: profileFields },
      { new: true, upsert: true }
    );
    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM