mongoose Multer:“ENOENT:没有这样的文件或目录”

bpzcxfmw  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(112)

我总是出错,不知道出了什么问题。我正在尝试通过 Mongoose 上传多个文件。我是新来的,任何帮助都将不胜感激,谢谢。
这是我的app.js

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, __dirname + '/uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})
const upload = multer({ storage: storage })

个字符
HTML(.ejs文件)

<form action="/movies" enctype="multipart/form-data" method="POST">
  <label for="title">Title:</label>
  <input type="text" name="postTitle" required>
    
  <label for="postImages">Choose file(s):</label>
  <input type="file" name="postImages" accept="image/*" multiple>      
    
  <label for="content">Content:</label>
  <textarea name="postContent" rows="8" required></textarea>
    
  <input type="submit" value="Submit">
</form>

架构

const mongoose = require('mongoose');

const imageSchema = new mongoose.Schema({
  name: String,
  alt: String,
  image:
  {
      data: Buffer,
      contentType: String
  }
});
const Image = mongoose.model('Image', imageSchema);
module.exports = {
  Image
};

hivapdat

hivapdat1#

因为你使用了multer的array()方法,所以通过req.files得到一个file对象数组。因此,要对每个文件执行操作,我们需要迭代req.files数组。我更新你的代码如下:

app.post('/movies', upload.array('postImages', 12), function (req, res) {
  const title = req.body.postTitle;
  const content = req.body.postContent;
  const files = req.files; // files is an Array object

  files.forEach(file => {
    const newImage = new Image({
      name: title,
      alt: title,
      image: {
        data: fs.readFileSync(
          path.join(__dirname + "/uploads/" + file.filename)
        ),
        contentType: "image/png",}
    });

    newImage.save((err) => {
      if (err) {
        console.log(err);
      }
    });
  });
  
  res.redirect("/movies");
});

字符串

相关问题