简体   繁体   中英

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 {}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM