【问题标题】:Issue to submit CSV file to DB via POST Axios & React-Final-Form通过 POST Axios 和 React-Final-Form 向数据库提交 CSV 文件的问题
【发布时间】:2019-09-19 16:45:50
【问题描述】:

我需要使用 React-Final-Form 和 Axios 将 CSV 的内容保存到数据库表中。

我尝试在不使用 Final-Form 或 Axios 的情况下创建一个简单的 HTML,并且提交到 DB 工作正常。 问题是当我尝试将 CSV 的内容传递给将处理 POST 调用的函数时。 见以下代码:

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;

如果我删除以上所有内容并在我的 JoinTesting 组件中使用这个 HTML,它可以正常工作,但我无法处理错误(如果有的话)

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

请注意:CSV 文件只有一个简单的 1 列,其中包含一系列电子邮件地址。 这是 POST 请求所期望的:

标题:

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

身体

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

成功调用的预期 API 响应是:

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

我希望有人可以提供帮助。 乔治

【问题讨论】:

  • 您遇到的错误是什么?

标签: reactjs form-data react-final-form


【解决方案1】:

如果您不使用 html form + HTTP POST + encType="multipart/form-data",那么您需要自己处理文件上传。

一种方法:获取input 组件的引用,监听更改,当发生更改时,从输入引用中获取文件名,读取文件,保存数据。这是一个组件:

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}
    />
  );
}

在Field 组件中使用它,表单状态将包含文件:

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

handleSubmitOnClick 也可以获取整个 values 对象。您的值应如下所示:

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

因此,将handleSubmitOnClick 函数更改为:

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

这里是a codesandbox。

【讨论】:

  • 这周我会测试它,让你。感谢您的回答。
  • 嘿 Istvan,我收到此错误消息:未捕获类型错误:无法构造“文件”:提供的值无法转换为序列。它发生在线 data.append.....
  • 嗨 @Joe,我已经更新了答案(handleInputChange 和 handleSubmitOnClick 函数)并包含了一个代码框链接。
  • 嗨@Istvan Szasz,返回的文件是空的。 { "invitation": { "file": {} } },它没有附加文件的内容。 FormData: {} 为空
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 2020-07-18
  • 2021-09-15
  • 2017-07-05
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多