sokida
sokida

Reputation: 539

Upload csv file and send it to api with react js

I'm using react js version 17, I want to upload file and send it to my node js api. I have two buttons, The first button used to read the first line in the file, the second button is for the call to the back end server to save the file in the database as a file I have create a formData to set my formData file input always i got empty object.

Here's my code :

 const [myFile,setMyFile] = useState();
 const [headers,setHeaders] = useState();

 const readFile = e =>{
      const file = e.target.files[0];
        const reader = new FileReader();

        reader.onload = function(e) {
            const text = e.target.result;
            const headers = text.slice(0,text.indexOf('\n')).split(';');
             
            setHeaders(headers)
            
        }
        reader.readAsText(file);
        setMyFile(file) 
 }


 const callApi = e => {
            const formData = new FormData(); 
            formData.append( 
                "file", 
                myFile, 
            ); 
            axios.post('localhost:8080/uploadFile', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
         })            
        }

My formData always return an empty object {}

Upvotes: 0

Views: 3789

Answers (1)

Sandeep Jain
Sandeep Jain

Reputation: 1262

Upload logic in react js to send csv in API to backend :

import React, { Component } from "react";
import axios from 'axios';
import AppContext from './AppContext';

const SERVER_URL = process.env.REACT_APP_SERVER_URL;
const PROTOCOL = process.env.REACT_APP_PROTOCOL;
const PORT = process.env.REACT_APP_PORT;

class UploadMeasure extends Component {
    constructor() {
        super();
        this.state = {
            csvfile: undefined
        };
        this.updateData = this.updateData.bind(this);
    }

    handleChange = event => {
        this.setState({
            csvfile: event.target.files[0]
        });
    };

    importCSV = () => {
        const { csvfile } = this.state;
        console.log(csvfile);
        var fileName = csvfile.name;
        const formData = new FormData();
        formData.append(
            "fileChooser",
            csvfile,
        );
        axios.post(PROTOCOL + "://" + SERVER_URL + ":" + PORT + "/uploadMeasures/" + AppContext.username + "?&fileName=" + fileName, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => { // then print response status
            console.log(res)
            if (res === 'success') {
                alert("File data uploaded Successfully");
            } else {
                if (res === 'Error') {
                    alert("Please ensure that your CSV file is formatted using the correct template, if you have any doubt contact the support team.");

                } else {
                    console.log(res)
                }

            }

        })
    };

    

    updateData(result) {
        var data = result.data;
        console.log(data);
    }

    render() {
        console.log(this.state.csvfile);
        return (
            <div className="App">
                <h2>Import CSV File!</h2>
                <input
                    className="csv-input"
                    type="file"
                    ref={input => {
                        this.filesInput = input;
                    }}
                    name="file"
                    placeholder={null}
                    onChange={this.handleChange}
                />
                <p />
                <button onClick={this.importCSV}> Upload now!</button>
            </div>
        );
    }
}

export default UploadMeasure;

Upvotes: 1

Related Questions