kzacharczyk
kzacharczyk

Reputation: 41

send an image file from react to node.js

I am currently working upload a profile picture and save the picture at aws s3 bucket.

When I send an image file through Postman, there were no error just works fine. I was able to upload a file to multer and aws s3.

However, when I tried to upload a picture through react front-end, It doesn't show any file. req.file is undefined.

I tried to figure this problem for weeks but still have no clue. I tried data.append profilepic[0] but it still didn't work.

React Code

 clickSubmit = event => {
        event.preventDefault()
        
        const {profilepic, fname, lname, password, passwordconfirm} = this.state
        const data = new FormData();
        console.log(profilepic[0]);
        // data.append('profilepic', profilepic[0], profilepic[0].name);
        const user ={
            fname,
            lname,
            password,
            passwordconfirm,
            profilepic
        };
        console.log(user);
        this.signup(user).then(data => {
            console.log(data)
            if(data.error) {
                this.setState({error: data.error});
            }
            else{
                this.setState({
                    fname:"",
                    lname: "",
                    password: "",
                    error: "",
                    open: true,
                    passwordconfirm: "",
                    // profilepic: [],
                });
            }
                
        });

    };

    onDrop(picture) {
        this.setState({
            profilepic: picture,
        });
        console.log(this.state.profilepic);
    }

    signup = user => {
        return fetch("http://localhost:3003/auth/mtregister",{
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "http://localhost:3003"

            },
            body: JSON.stringify(user)
        })
        .then(response => {
            return response.json();
          })
          .catch(err => console.log(err));
    }

inspect console shows file information console from front-end

mtregister node.js

const db = require('../../dbconfig.js');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const {promisify} = require('util');
const nodemailer = require('nodemailer');
const multer = require('multer');
const fs = require('fs');
const aws = require('aws-sdk');

aws.config.update({
    accessKeyId: process.env.AWS_KEY,
    secretAccessKey: process.env.AWS_SECRET_KEY,
    region: 'us-east-1',
});

//Creating a new instance of S3:
const s3= new aws.S3();

// Set up Multer Storage
const storage = multer.diskStorage({
    destination: "../../public/images",
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
    }
  })

const upload = multer({ storage: storage });

/*mentor register*/
exports.mtregister = [upload.single('profilepic'), async(req,res)=>
{
    console.log(req.body);
    console.log(req.file);
....
}

the output of console.log(req.body);console.log(req.file); is empty [ {} ] and undefined. console.log results

Upvotes: 0

Views: 949

Answers (1)

Berna
Berna

Reputation: 21

I recommend use Axios to make http request from React. The Docummentation is good.

Example from: https://www.nicesnippets.com/blog/react-js-file-upload-example-with-axios

import React from 'react'
import axios from 'axios';

class FileUpload extends React.Component{

    constructor(){
        super();
        this.state = {
            selectedFile:'',
        }

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event) {
        this.setState({
            selectedFile: event.target.files[0],
          })
    }

    submit(){
        const data = new FormData() 
        data.append('file', this.state.selectedFile)
        console.warn(this.state.selectedFile);
        let url = "http://localhost:8000/upload.php";

        axios.post(url, data, { // receive two parameter endpoint url ,form data 
        })
        .then(res => { // then print response status
            console.warn(res);
        })

    }

    render(){
        return(
            <div>
                <div className="row">
                    <div className="col-md-6 offset-md-3">
                        <br /><br />

                            <h3 className="text-white">React File Upload - Nicesnippets.com</h3>
                            <br />
                            <div className="form-row">
                                <div className="form-group col-md-6">
                                    <label className="text-white">Select File :</label>
                                    <input type="file" className="form-control" name="upload_file" onChange={this.handleInputChange} />
                                </div>
                            </div>

                            <div className="form-row">
                                <div className="col-md-6">
                                    <button type="submit" className="btn btn-dark" onClick={()=>this.submit()}>Save</button>
                                </div>
                            </div>
                    </div>
                </div>
            </div>
        )  
    }
}

export default FileUpload;

Upvotes: 2

Related Questions