Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image using javascript fetch api and express multer

Tags:

I am working in a reactjs application where i have to upload user image. I am getting file on onChange event of file input and passing it parent component and parent component will make a post request using the data

Server side I am using express and multer for file upload and client side using fetch api to upload the image.

Thanks in advance :)

like image 348
Piyush Patel Avatar asked Nov 14 '17 17:11

Piyush Patel


1 Answers

I figure it out To upload an file/image to multer we need a form enctype="multipart/form-data" without that it wont work with multer

I am getting file from a child component then 1) i have created a empty form with the encType="mutipart/form-data" 2) when i received the file i create a new FormData(with ref to myform) 3) then append key and value in the formData 4) create fetch.post() and it works :)

for ref submitting the code

React Parent component Upload.js

import React, { Component } from 'react'

import { ImageWithoutForm } from "../app/components/ImageUpload";


export default class UploadFile extends Component {
    onImageLoad(e){
        console.log('onImageLoad', e.target.files[0]);
        this.uploadForm(e.target.files[0]);
    }

    uploadForm(file){
        let form = new FormData(this.refs.myForm);
        form.append('myImage', file);
        fetch('/upload-image', {
          method: 'POST',
          body: form
        }).then(res => console.log('res of fetch', res));
    }

  render() {
    return (
      <div>
        <h4>Upload Image</h4>
        <ImageWithoutForm onImageLoad={(e)=>this.onImageLoad(e)} />
        <form id="upload_form" ref="myForm"  encType="multipart/form-data">
        </form>
      </div>
    )
  }
}

React Child Component with input to load the file ImageWithoutForm.js

import React, { Component } from 'react'

export  class ImageWithoutForm extends Component {

    handleSubmit(e){
        this.props.onImageLoad(e);
    }


  render() {
    return (
      <div>
            <input type="file" onChange={(e)=>this.handleSubmit(e)}/>
      </div>
    )
  }
}

Express Route file taken from someone github repo and customized UploadImage.js

const express = require('express');
const multer = require('multer');
const path = require('path');

// Set Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

// Init app
const app = express.Router();


// Public Folder
app.use(express.static('./public'));


app.post('/', (req, res) => {
    console.log('handling upload image');
  upload(req, res, (err) => {
    if(err){
      console.log('first err', err);
      res.send({
        msg: err
      });
    } else {
      if(req.file == undefined){
        console.log('Error: No File Selected!')
        res.send({
          msg: 'Error: No File Selected!'
        });
      } else {
        console.log('File Uploaded!')
        res.send({
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

module.exports = app;

and in my express app.js just require the route file ImageUpload.js

and map to the route like this

var uploadImage = require('./routes/UploadImage');
server.use('/upload-image', uploadImage);
like image 137
Piyush Patel Avatar answered Sep 23 '22 12:09

Piyush Patel