【问题标题】:Upload image then update with Multer and Express.js上传图片,然后使用 Multer 和 Express.js 进行更新
【发布时间】:2019-01-19 15:12:18
【问题描述】:

所以我已经完成了从here 上传带有MulterExpress.js 的图像的阶段。现在,如果我编辑具有该图像的文章,我会得到正确的图像。但是,我要做的是,如果图像仍然相同,则不要执行任何操作,否则取新上传的图像。

我的问题是 input[type="file"] 不接受 attr value 手动设置。我也读过这个question,但我不知道它是否与我的问题有关!

我提交编辑后得到的是Cannot read property 'filename' of undefined。但是,我从请求中正确获取了所有其他表单字段。

我正在使用 MongoosemethodOverride 进行 PUT 和 DELETE requests

穆特

const multer = require('multer');
const storage = multer.diskStorage({
  destination: (_req, _file, done) => {
    done(null, path.join(__dirname, './../../public/uploads/'));
  },
  filename: (_req, file, done) => {
    done(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`,
    );
  },
});
const upload = multer({
  storage
});

对于 POST 请求

router.post('/add', authenticate, upload.single('image'), (req, res) => {

    const userId = req.user.id;

    const body = req.body;

    const title = body.title;
    const content = body.content;
    const featured = body.featured;
    const image = req.file.filename;

    const newPost = new Post({
      title,
      content,
      image,
      userId,
      featured
    });

    newPost
      .save()
      .then(post => {
        if (!post) {
          return req.flash('error', 'Unable to add article!!!');
        }
        req.flash('success', 'Added article successfully');
      })
      .catch(err => {
        return req.flash('error', 'Unable to add article!!!');
      });

    res.redirect('/posts');
  },
);

对于 PUT 请求

router.put(/post/edit/:id', authenticate, upload.single('image'), (req, res) => {
    const id = req.params.id;

const body = req.body;

console.log('body:', body);
console.log('req:', req);

const title = body.title;
const content = body.content;
const featured = body.featured;
const image = req.file.filename;

Post.findOneAndUpdate(id,
  {
    $set: {
      title,
      content,
      featured,
      image
    }
  },
  { new: true }
).then(post => {
    req.flash('success', 'Edits submitted successfully');
    res.redirect('/posts');
  })
  .catch(err => {
    return req.flash('error', 'Unable to edit article');
  }); });

【问题讨论】:

    标签: node.js express file-upload mongoose multer


    【解决方案1】:
    const multer = require('multer');
    
     var storage = multer.diskStorage({
        destination: (req, file, callback) => {
        callback(null, 'public/uploads/')
     },
     filename: (req, file, callback) => {
        var filetype = file.mimetype;
        var fileformate = filetype.split("/")[1];
        callback(null, Date.now() + '.' + fileformate);
     }
    });
    var upload = multer({ storage: storage });
    

    【讨论】:

    • 我不明白你的回答。你的和我已经在我的问题中发布的有什么区别??
    【解决方案2】:

    您只需要使用if (req.file) 检查是否有附加到请求的文件并相应地修改数据库查询。 所以你的帖子编辑代码可以是这样的:

    router.put('/post/edit/:id', authenticate, upload.single('image'), (req, res) => {
        const id = req.params.id;
    
        const body = req.body;
    
        console.log('body:', body);
        console.log('req:', req);
    
    
        const title = body.title;
        const content = body.content;
        const featured = body.featured;
    
        const updates = {
            title,
            content,
            featured
        };
    
        if (req.file) {
            const image = req.file.filename;
            updates.image = image;
        }
    
    
        Post.findOneAndUpdate(id, {
                $set: updates
            }, {
                new: true
            }).then(post => {
                req.flash('success', 'Edits submitted successfully');
                res.redirect('/posts');
            })
            .catch(err => {
                return req.flash('error', 'Unable to edit article');
            });
    });
    

    【讨论】:

    • 我也遇到了类似的问题,并按照你的方法。但是在 PUT/PATCH 请求的情况下,req.files 对我来说总是undefined。你能帮忙吗?
    【解决方案3】:

    来自multer.single(fieldname)的文档

    接受名称为 fieldname 的单个文件。单个文件将存储在 req.file 中。


    因为您正在执行upload.single('image'),所以您的multer 将接受带有name 图像 的文件并将其存储到req.file.image。但是,您使用 filename 引用它。因此,您应该将req.file.filename 替换为req.file.image

    此外,在上传新文件或编辑时,您需要在使用 multer 处理它之前检查 file 是否存在,以避免 property of undefined 错误。

    if (req.file) {
      // your code
    }
    

    【讨论】:

    • 谢谢兄弟。对我来说很好的解释,就像一个魅力 (Y)。
    猜你喜欢
    • 2016-06-14
    • 2021-05-30
    • 1970-01-01
    • 2018-11-23
    • 2017-12-21
    • 1970-01-01
    • 2018-09-17
    • 2018-10-23
    • 2018-12-16
    相关资源
    最近更新 更多