node.js - How to upload image using javascript fetch api and express multer - Stack Overflow

admin2025-04-19  0

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 ponent and parent ponent 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 :)

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 ponent and parent ponent 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 :)

Share Improve this question asked Nov 14, 2017 at 17:51 Piyush PatelPiyush Patel 1,24015 silver badges19 bronze badges 2
  • I used this module for file uploads using socket.io: npmjs./package/socketio-file-upload – JJJ Commented Nov 14, 2017 at 18:07
  • @ricky I have tried the multer example in which i can easily upload file using a Form Submit but I need to use it without the form submit for example using a function to make a post request there its not working I dont know how to send data with FormData etc npmjs./package/multer – Piyush Patel Commented Nov 15, 2017 at 2:36
Add a ment  | 

1 Answer 1

Reset to default 4

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 ponent 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 ponent Upload.js

import React, { Component } from 'react'

import { ImageWithoutForm } from "../app/ponents/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);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745063132a282820.html

最新回复(0)