Multer:文件路径不正确

时间:2018-10-31 11:45:53

标签: javascript node.js multer

我在我的node js应用程序中添加了multer,它运行良好,只是我需要存储在db中的图像路径不正确。找不到问题,显然是我犯了一些愚蠢的错误。

这是我的搅拌器设置

const multer = require('multer');

const storage = multer.diskStorage({
  destination: './public/images',
  filename: function(req, file, next){
      next(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage});

这是我用来存储路径的方式

router.post('/add', upload.single('myImage'), function(req, res){
  req.checkBody('title','Title is required').notEmpty();
  //req.checkBody('author','Author is required').notEmpty();
  req.checkBody('body','Body is required').notEmpty();

  // Get Errors
  let errors = req.validationErrors();

  if(errors){
    res.render('add_article', {
      title:'Add Article',
      errors:errors
    });
  } else {
    let article = new Article();
    //var date = new Date();
    article.title = req.body.title;
    article.author = req.user._id;
    article.body = req.body.body;
    article.descript = req.body.descript;
    article.category = req.body.category;  
    article.date = getDate();
    article.time = getTime();
    article.comments = 0;   
    article.img = req.file.path;   
    console.log(req.file);
    article.save(function(err){
      if(err){
        console.log(err);
        return;
      } else {
        req.flash('success','Article Added');
        res.redirect('/');
      }
    });
  }
});

从这里您可以看到该路径不正确,我无法在GET上使用它

{ _id: 5bd993756373a5182460aa2a,
  title: 'Sport 5',
  author: '5acab056708e0d1248cba6ed',
  body: 'sadddddddddddddd213',
  descript: 'dsadas',
  category: 'sport',
  date: '2018/10/31',
  time: '12:35',
  comments: 0,
  img: 'public\\images\\1540985717747-nike_logo_slogan_sport_advertising_42643_1280x1024.jpg',
  __v: 0 }

2 个答案:

答案 0 :(得分:1)

在Windows中会发生这种情况,因为Windows中的任何文件路径都只有反斜杠,但是要使文件可通过url访问,它必须带有反斜杠。因此,只需使用以下代码将所有反斜杠转换为正斜杠

const imageUrl = req.file.path.replace(“ \”,“ /”);

答案 1 :(得分:0)

Multer在您的终端上正常工作,您只需要将系统路径转换为可访问的url。

这会为您提供帮助。

article.comments = 0;
let fileUrl = req.file.path.replace(/\\/g, "/").substring("public".length);
article.img = fileUrl;