简体   繁体   中英

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
}

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.

const express = require('express');
const multer = require('multer');
const path = require('path');
const router = express.Router()

// Image Upload
const imageStorage = multer.diskStorage({
    destination: 'images', // Destination to store image 
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname))
        // file.fieldname is name of the field (image), path.extname get the uploaded file extension
    }
});

const imageUpload = multer({
    storage: imageStorage,
    limits: {
        fileSize: 1000000   // 1000000 Bytes = 1 MB
    },
    fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg)$/)) {     // upload only png and jpg format
            return cb(new Error('Please upload a Image'))
        }
        cb(undefined, true)
    }
})  

// For Single image upload
router.post('/uploadImage', imageUpload.single('image'), (req, res) => {
    res.send(req.file)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

// For Multiple image upload
router.post('/uploadBulkImage', imageUpload.array('images', 4), (req, res) => {
    res.send(req.files)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

// ---------------------------------------------------------------------------- //

// Video Upload
const videoStorage = multer.diskStorage({
    destination: 'videos', // Destination to store video 
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname))
    }
});

const videoUpload = multer({
    storage: videoStorage,
    limits: {
        fileSize: 10000000   // 10000000 Bytes = 10 MB
    },
    fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(mp4|MPEG-4)$/)) {     // upload only mp4 and mkv format
            return cb(new Error('Please upload a Video'))
        }
        cb(undefined, true)
    }
})

router.post('/uploadVideo', videoUpload.single('video'), (req, res) => {
    res.send(req.file)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

module.exports = router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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