FormData sends null to my back even though I get a file when I use formData.get('file')

huangapple go评论65阅读模式
英文:

FormData sends null to my back even though I get a file when I use formData.get('file')

问题

以下是您要翻译的部分:

"Hi I want to send a file to parse to my backend using Flask.
If I send the file using Postman it works correctly but when I try to send it through my React app it does not go through."

<div>
    <label htmlFor="file" style={{ marginBottom: '0.5rem', display: 'block' }}>
        上传简历
    </label>
    <input
        className={styles.inputstyle}
        type="file"
        name="file"
        onChange={handleFileChange}
        style={{ marginBottom: '0.5rem' }}
    />
    <button onClick={handleFileChange}>发送</button>
</div>

下面是handleFileChange方法的代码:

const handleFileChange = (e) => {
    let file = e.target.files[0]
    const formData = new FormData()
    formData.append('file', file)

    console.log(formData.get('file')) // 打印正确的文件
    
    axios.post('http://127.0.0.1:8000/user-file', { data: formData }, {
        headers: {
            'Content-type': 'multipart/form-data',
        }
    })
    .then((response) => {
        console.log(response.data)
    })
};

我在后端收到一个错误:

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file'

我忘记了请求中的哪些部分吗?

Axios版本:1.4.0

编辑:添加后端路由的代码:

@app.route("/user-file", methods=["POST"])
def file_to_resume():
    test = request
    test = request.files['file'] # 在Postman中可以工作
    data = extract_text(test.filename)
    data_parsed = parse_resume(data)
    return jsonify(data_parsed), 200
}
英文:

Hi I want to send a file to parse to my backend using Flask.
If I send the file using Postman it works correctly but when I try to send it through my React app it does not go through.

                     &lt;div&gt;
                        &lt;label htmlFor=&quot;file&quot; style={{marginBottom:&#39;0.5rem&#39;, display:&#39;block&#39;}}&gt;
                            Upload Resume
                        &lt;/label&gt;
                        &lt;input
                        className={styles.inputstyle}
                        type=&quot;file&quot;
                        name=&quot;file&quot;
                        onChange={handleFileChange}
                        style={{ marginBottom: &#39;0.5rem&#39; }}
                        /&gt;
                        &lt;button onClick={handleFileChange}&gt;send&lt;/button&gt;
                    &lt;/div&gt;

The handleFileChange method below:

    const handleFileChange = (e) =&gt; {
        let file = e.target.files[0]
        const formData = new FormData()
        formData.append(&#39;file&#39;, file)

        console.log(formData.get(&#39;file&#39;)) // prints the correct file
        
        axios.post(&#39;http://127.0.0.1:8000/user-file&#39;, {data: formData},
        {
            headers : {
            &#39;Content-type&#39;: &#39;multipart/form-data&#39;,
            }
        }
        )
        .then((response) =&gt; {
            console.log(response.data)
        })
      };

I get an error in my backend:

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not 
understand.
KeyError: &#39;file&#39;

Did I forget something think in my request?
Axios version: 1.4.0

EDIT: Added backend code route

@app.route(&quot;/user-file&quot;, methods=[&quot;POST&quot;])
def file_to_resume():
    test = request
    test = request.files[&#39;file&#39;] # works with postman
    data = extract_text(test.filename)
    data_parsed = parse_resume(data)
    return jsonify(data_parsed), 200

答案1

得分: 1

代码已翻译如下:

问题在于你正在发送一个包含 `data` 键的对象,但你应该只发送 `formData` 本身,所以请将你的代码更改为:

const handleFileChange = (e) => {
  let file = e.target.files[0]
  const formData = new FormData()
  formData.append('file', file)
  axios.post('http://127.0.0.1:8000/user-file', formData, // 这里是更改
    {
      headers: {
        'Content-type': 'multipart/form-data',
      }
    }
  ).then((response) => {
    console.log(response.data)
  })
};
英文:

Well, the issue is that you are sanding an object with a data key inside, but you sould just send formData itself, so chenge your code to be

const handleFileChange = (e) =&gt; {
  let file = e.target.files[0]
  const formData = new FormData()
  formData.append(&#39;file&#39;, file)
  axios.post(&#39;http://127.0.0.1:8000/user-file&#39;, formData, // Here is the change
    {
      headers: {
        &#39;Content-type&#39;: &#39;multipart/form-data&#39;,
      }
    }
  ).then((response) =&gt; {
    console.log(response.data)
  })
};

huangapple
  • 本文由 发表于 2023年6月26日 21:10:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定