简体   繁体   中英

reactjs component for uploading csv file to server is not working properly

I am learning reactjs for building web application. Basically, my goal is I want to create reactjs component that can upload local csv file to the server (I created server js). To do so, I come across a basic reactjs component implementation down below:

 import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { var FormBox = React.createClass({ getInitialState: function () { return { file: '', FilePreviewUrl: '' }; }, pressButton: function () { e.preventDefault(); console.log('handle uploading-', this.state.file); }, uploadCSV: function (e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, FilePreviewUrl: reader.result }); } reader.readAsDataURL(file); }, render: function () { let {FilePreviewUrl} = this.state; let FilePreview = null; if (FilePreviewUrl) { FilePreview = (<img src={FilePreviewUrl} />); } else { FilePreview = (<div className="previewText">Please select an Json for Preview</div>); } return ( <div> <form action='.' enctype="multipart/form-data"> <input type='file' onChange={this.uploadCSV}/> <button onClick={this.pressButton}> Get it </button> </form> <div className="filePreview"> {FilePreview} </div> </div> ) } }) } ReactDOM.render(<FormBox />, document.getElementById('root')) export default App; 

but when I run my component I got an error which is not intuitive to me. Here is the error:

Failed to compile.

./src/App.js
  Line 6:  Parsing error: Unexpected token

  4 | 
  5 | class App extends Component {
> 6 |   var FormBox = React.createClass({
    |       ^
  7 |     getInitialState: function () {
  8 |       return {
  9 |         file: '',

How to fix this error? How to make above implementation works for the purpose of uploading csv file to the server? any idea?

clarification :

I am doing this because I intend to upload local csv file to the server and trigger API key that provided at back-end to populate the csv data to the database. I am newbie to reactjs so my above code may not be well shaped. can anyone help me how to make this works? any help would be appreciated.

goal :

Sine few smart people in SO community suggested me that I was wrong about the implementation. What I am actually trying to do is to upload local files to server. How can I modify above code for creating reactjs component for uploading file to server?

You are declaring a class inside a class, and you shouldn't use React.CreateClass anymore since its deprecated. Also, you have to import ReactDOM in order to use it (at the bottom of your file).

I don't know why you need the App component, but I editted your code to include the correct syntax (Can't really check the csv upload logic).

I'm assuming that you're using some sort of a request helper library. in this example I use axios .

I don't really know the FileReader api, but if I understand it correctly, onloadend returns the file data. After that we can send the data to the server (where we use axios.post).

The next step would be to define an endpoint on the server (I'm assuming express) that gets the data and saves it to the server using the fs module (HINT: fs.writeFile).

 import ReactDOM from 'react-dom'; import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import axios from 'axios'; class App extends Component { render() { return ( <FormBox /> ) } } class FormBox extends Component { constructor(props) { super(props); this.state = { file: '', filePreviewUrl: '' } } uploadCSV(e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; reader.onloadend = (error, data) => { if (error) throw new Error('Oops! something went wrong!'); axios.post('http://your-link-goes-here/', {data: data}).then(data => { this.setState({ file: file, filePreviewUrl: reader.result }); }) } reader.readAsDataURL(file); } render() { let {filePreviewUrl} = this.state; let filePreview = null; if (filePreviewUrl) { filePreview = (<img src={filePreviewUrl} />); } else { filePreview = (<div className="previewText">Please select an Json for Preview</div>); } return ( <div> <form action='.' enctype="multipart/form-data"> <input type='file' onChange={this.uploadCSV}/> <button onClick={(e) => this.uploadCSV(e)}> Get it </button> </form> <div className="filePreview"> {filePreview} </div> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')) 

So you're mixing up some syntax for declaring React components. Here it is rewritten with a working codesandbox: https://5y03xnvpqx.codesandbox.io/

import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class FormBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      file: "",
      filePreviewUrl: ""
    };
    this.pressButton = this.pressButton.bind(this);
    this.uploadCSV = this.uploadCSV.bind(this);
  }

  pressButton(e) {
    e.preventDefault();
    console.log("handle uploading-", this.state.file);
  }

  uploadCSV(e) {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {
      this.setState({
        file: file,
        filePreviewUrl: reader.result
      });
    };
    reader.readAsDataURL(file);
  }

  render() {
    const { filePreviewUrl } = this.state;
    let FilePreview = null;
    if (filePreviewUrl) {
      FilePreview = <img src={FilePreviewUrl} />;
    } else {
      FilePreview = (
        <div className="previewText">Please select an Json for Preview</div>
      );
    }
    return (
      <div>
        <form action="." enctype="multipart/form-data">
          <input type="file" onChange={this.uploadCSV} />
          <button onClick={this.pressButton}> Get it </button>
        </form>
        <div className="filePreview">{FilePreview}</div>
      </div>
    );
  }
}

function App() {
  return (
    <div className="App">
      <FormBox />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You'll notice that I put filePreviewUrl in lower case. By convention, React components are uppercase, so when you see something that's uppercase, you expect that it's eventually going to become a component. If that's not the case, best to leave it lowercase.

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