Issue to submit CSV file to DB via POST Axios & React-Final-Form

徘徊边缘 提交于 2019-12-11 15:27:32

问题


I need to save the content of a CSV into a database table by using React-Final-Form and Axios.

I have tried to create a simple HTML without using Final-Form or Axios and the submission to the DB works fine. The problem is when I try to pass the content of the CSV to a function which will handle the POST call. See code below:

import React, { Fragment } from "react";
import { Form, Field } from "react-final-form";
import createDecorators from "final-form-focus";

const handleSubmitOnClick = file => {
   const url = 'http://localhost:3000/api/v1/invitations/upload';
   const data = new FormData();
   data.append('file', new File([file], { type: 'text/csv' }));

   return axios.post(url, data, {
     headers: {
       'content-type': 'multipart/form-data'
     }
   })
  .then(response => console.log(response))
  .catch(error => console.log(error));
}

const JoinTesting = () => 

  <Fragment>
    <h1>Join Testing Page</h1>
    <Form 
      onSubmit={handleSubmitOnClick}
      decorators={[focusOnError]}
    >
      {
        ({ 
          handleSubmit, 
          values, 
          submitting,
        }) => (
        <form onSubmit={handleSubmit} encType="multipart/form-data">
          <Field 
            name='invitation[file]'
            placeholder='Upload csv file'
            validate={required}
          >
            {({ input, meta, placeholder }) => (
              <div className={meta.active ? 'active' : ''}>
                <label>{placeholder}</label>
                <input {...input} 
                  type='file' 
                  placeholder={placeholder} 
                  className="join-field-input"
                />
                {meta.error && meta.touched && <span className="invalid">{meta.error}</span>}
                {meta.valid && meta.dirty && <span className="valid">Great!</span>}
              </div>
            )}
          </Field>

          <button 
            type="submit"
            className="join-button"
            disabled={submitting}
          >
            Submit
          </button>

          <pre>{JSON.stringify(values, 0, 2)}</pre>
        </form>
      )}
    </Form>
  </Fragment>

export default JoinTesting;

If I remove ALL the above and I just use this HTML within my JoinTesting component, it works fine but I can't handle the errors (if any)

<form action="http://localhost:3000/api/v1/invitations/upload" method="post" encType="multipart/form-data">
    Select CSV to upload:
    <input type="file" name="invitation[file]" id="fileToUpload" />
    <br></br>
    <input type="submit" value="Upload CSV" name="submit" />
  </form>

PLEASE NOTE: The CSV file has only a simple 1 column with a sequence of email addresses. This is what the POST request expects:

Headers:

Content-Type: application/json
Accept: application/json

Body

{
  "invitation": {
    "file": "Email\nuser_1@gmail.com\nuser_2@gmail.com\nuser_3@gmail.com\nuser_4@gmail.com\n"
  }
}

The API response expected for a success call is:

{
  "success": true,
  "emails": [
    "user_1@gmail.com",
    "user_2@gmail.com",
    "user_3@gmail.com",
    "user_4@gmail.com"
  ]
}

I hope someone can help. George


回答1:


If you're not using html form + HTTP POST + encType="multipart/form-data", then you'll need to handle the file upload yourself.

One way to do it: get reference to the input component, listen to changes, when a change happens get the filename from the input reference, read the file, save the data. Here's a component for that:

function FileInput(props) {
  const fileInput = useRef(null);
  const setRef = ref => {
    fileInput.current = ref;
  };

  async function handleInputChange() {
    const { files } = fileInput.current;
    props.onChange(files[0]);
  }

  return (
    <input
      ref={setRef}
      type="file"
      placeholder={props.placeholder}
      className="join-field-input"
      onChange={handleInputChange}
    />
  );
}

Use this within the Field component, and the form state will contain the file:

<Field name="invitation[file]" placeholder="Upload csv file">
    {({ input, meta, placeholder }) => (
       // ...
        <FileInput {...input} placeholder={placeholder} />
       // ...
    )}
</Field>

Also the handleSubmitOnClick gets the whole values object. Your values should look something like this:

values = { invitation: { file: {} } } 

So, change the handleSubmitOnClick function to:

const handleSubmitOnClick = values => {
  const data = new FormData();
  const { file } = values.invitation;
  data.append('file', file, file.name);
  // ...
}

Here's a codesandbox.



来源:https://stackoverflow.com/questions/58015594/issue-to-submit-csv-file-to-db-via-post-axios-react-final-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!