简体   繁体   English

使用multer显示上传的图片

[英]Display uploaded image with multer

I am new in NodeJS and I am working on a projet using express, ejs and Multer (handle multipart/form-data) in order to upload a picture (single >> profile picture). 我是NodeJS的新手 ,我正在使用express,ejs和Multer (处理multipart / form-data)来处理图片,以便上传图片(单个>>个人资料图片)。 I have been trying to display the uploaded file (image) in a view without success. 我一直试图在视图中显示上载的文件(图像),但没有成功。 I have all the information regarding the uploaded file (req.file) but I can't do anything with it. 我拥有有关上传文件(req.file)的所有信息,但是我无法执行任何操作。

//route.js 
   app.post('/upload_picture', isLoggedIn, upload.single('file'), function(req, res, next){
        res.render('image', {
              path: req.file.path
        });
      });



//image.ejs
<section id="upload">
    <img class="uploaded-image" src="<%= path %>" alt="Image name: <%= path %>"/>
  </section>

Could somebody help me please. 有人可以帮我吗。

Best regards, Dona 最好的问候,多娜

So here is the solution, it worked for me ! 所以这里是解决方案,它为我工作!

var storage        = multer.diskStorage({
  destination: function(req, file, cb){
    cb(null, path.join(__dirname, PICTURE_FOLDER));
  },
  filename: function(req, file, cb){
    var filename = Date.now();
    switch (file.mimetype) {
      case 'image/png':
      filename = filename + ".png";
      break;
      case 'image/jpeg':
      filename = filename + ".jpeg";
      break;
      default:
      break;
    }
    cb(null, filename);
  }
});
var upload       = multer({ storage: storage});

app.post('/upload_picture', isLoggedIn, upload.single('file'), function(req, res, next){
    res.render('image', {
      path: req.file.path
    });
});

Best regards, Dona 最好的问候,多娜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM