英文:
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.
                     <div>
                        <label htmlFor="file" style={{marginBottom:'0.5rem', display:'block'}}>
                            Upload Resume
                        </label>
                        <input
                        className={styles.inputstyle}
                        type="file"
                        name="file"
                        onChange={handleFileChange}
                        style={{ marginBottom: '0.5rem' }}
                        />
                        <button onClick={handleFileChange}>send</button>
                    </div>
The handleFileChange method below:
    const handleFileChange = (e) => {
        let file = e.target.files[0]
        const formData = new FormData()
        formData.append('file', file)
        console.log(formData.get('file')) // prints the correct 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)
        })
      };
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: 'file'
Did I forget something think in my request?
Axios version: 1.4.0
EDIT: Added backend code route
@app.route("/user-file", methods=["POST"])
def file_to_resume():
    test = request
    test = request.files['file'] # 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) => {
  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, // Here is the change
    {
      headers: {
        'Content-type': 'multipart/form-data',
      }
    }
  ).then((response) => {
    console.log(response.data)
  })
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论