1

I am working on react/node for file uploading. I am not passing files into the API request but passing into the body part of the API request. My react code is like,

import React, { Component } from 'react';
import request from 'superagent';

class App extends Component {
constructor(props) {
    super(props);
    this.state = {
        image1: '',
    };

    this.handleUploadFile = this.handleUploadFile.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
};

handleUploadFile = (event) => {
    console.log("event", event.target);
    this.setState({
        image1: event.target.files[0],
    });
}

handleSubmit(e) {
    e.preventDefault();
    const dataDemo = {
        image: this.state.image1,
    };

    request
       .post(API_URL)
       .set('Content-Type', 'application/json')
       .send(dataDemo)
       .end(function (err, res) {
         console.log("err", err);
         console.log("res", res);
       })
}

render() {
    return (
        <div>
            <form encType="multipart/form-data">
                <div style={{width: '100%', marginTop: '10px'}}>
                    Image 1
                    <input name="image1" type="file" onChange={this.handleUploadFile} />
                </div>

                <div style={{width: '100%', marginTop: '10px'}}>
                    <input type="submit" name="submit" value="submit" onClick={this.handleSubmit} />
                </div>

            </form>
        </div>
    )
}`

I want to upload this image into server using Node/Express.js My API code in Node/Express.

So please help me how can I upload this image using API and save into server(inside the folder) using Node/Express.

My Node server code is like,

router.post(END_POINT,function (req, res) {
  //I want to add upload code here without any third party module and without req.files/req.file.
})

Please help me. Thank you in advance.

3
  • Express does not parse body by itself. You'll need a body parsing middleware. If you want to do that yourself, checkout the code of multer and/or body-parser modules. Commented Oct 23, 2017 at 12:12
  • Ok. So can we use here multer? Because problem is that here i describe only one image but there is multiple images. like 10 or more. Commented Oct 23, 2017 at 12:14
  • You need to rewrite the question, what you have right now is not clear regarding what you want to achieve. Regardless, multer can handle any number of files. Commented Oct 23, 2017 at 12:19

2 Answers 2

1

You can send multiple images using Multer.

uploadImage() {
 const options = new RequestOptions({ headers: headers });
 const inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#imageField');
 const fileCount: number = inputEl.files.length;
 const formData = new FormData();
 if (fileCount > 0) {
  formData.append('imageField', inputEl.files.item(0));
  }
}

Here imageField is the name of the input tag which looks like this:

<input type="file" name="imageField (change)="uploadImage()">

And then the backend code:

exports.uploadImage = (req, res) => {
var path;
var storage = multer.diskStorage({
    destination: function (req, res, next) {
        next(null, 'src/assets/images');
    },
    filename: function (req, file, next) {
        path = 'src/assets/images' + '.jpg';
        next(null, req.file.originalname + '.jpg');
    }
});
var upload = multer({ storage: storage }).any('imageField'); 
upload(req, res, error=> {
    console.log(req.files[0].path);
    if(error) {
        return res.json(error);
    }
    res.json({
        message: 'Uploaded !!',
        path: path
    })
 }) 
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are uploading multiple images , then you can use req.busboy with req.files

  • You can upload images with postman in body from from-data

    Which supports multiple image upload

  • You can also use multipart/form-data

    var form = req.form();

    form.append('file', '', { filename: 'myfile.txt',

    contentType: 'text/plain'

    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.