Search code examples
node.jsmongodbreactjsfsmulter

How to save and show the picture saved using Multer package in NodeJS?


I'm trying to save the image file using multer package.

Here is our registration.js which contains the registration form. The following scripts have no errors, but we don't know how to access the file in url or show the image to users (exactly how to save it with its MIME format).

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

export default class Registration extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    var config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    };

    var formData = new FormData();
    var imagefile = document.getElementById('profilePicture');
    formData.append('name',document.getElementById('name').value);
    formData.append('email',document.getElementById('email').value);
    formData.append('telegramId',document.getElementById('telegramId').value);
    formData.append('password',document.getElementById('password').value);
    formData.append('image', imagefile.files[0]);
    console.log(formData);
    axios.post('/registration', formData,config).then(function(res){
      console.log(res.data+'res');
    }).catch(console.error);
  }

  render() {
    return (<form className="registrationForm">
      <input type="text" name="name" id="name" required="required" placeholder="name" />
      <br/>
      <input type="email" id="email" required="required" placeholder="email"/>
      <br/>
      <input type="text" id="telegramId" required="required" placeholder="telegramID"/>
      <br/>
      <input type="password" id="password" required="required" placeholder="password"/>
      <br/>
      <input type="file" id="profilePicture"/>
      <br/>
      <button className="registerButton" onClick={this.handleSubmit}>Register</button>
    </form>)
  };
}

and this is server side code:

var multer  = require('multer')
var upload = multer({ dest: '../assets/uploads/' })


app.post('/registration',upload.single('image'), (req, res) => {
  // console.log(req.body);
  console.log(req.file);
});

and this is what the console has logged!

{ fieldname: 'image',
  originalname: 'sharif-logo-png-transparent.png',
  encoding: '7bit',
  mimetype: 'image/png',

  destination: 'uploads/',
  filename: 'e098a8370f444f321acd9aae668538fd',
  path: 'uploads\\e098a8370f444f321acd9aae668538fd',
  size: 271654
}

Solution

  • multer already takes care of saving the file to disk, so all you need to do is make that folder accessible to be used in <img> tags (or whatever you'll want to use to display them). A good solution would be express.static:

    const { static } = require('express');
    app.use('/images/', static('../assets/uploads/'));
    

    Then you can use them in your client-side code:

    <img src="/images/e098a8370f444f321acd9aae668538fd"></img>
    

    You don't have to handle the file at all in the .post('/registration') handler.