[英]400 (Bad Request) when sending a post request from React to Django
[英]POST 400 (BAD REQUEST) when uploading file between React and Flask
在我的 React 前端上傳 excel 文件並將其傳遞給 Flask api 時,不斷收到 400 錯誤。
Flask 后端路由是這樣的:
def post(self):
name = request.form['name']
file = request.files['file']
(....do stuff with file and name)
react API調用如下:
export const uploadFile = async (file) => {
const data = new FormData()
data.append("file", file)
data.append("name", 'temp')
const api_url = "http://localhost:5000/uploadFile"
const settings = {
method: "POST",
body: data
}
try {
const response = await fetch(api_url, settings)
const result = await response.json()
if (result.message === 'OK') {
return result
}
} catch (error) {
return "Unable to load file"
}
}
有趣的是 Flask 收到了 NAME 字段,但由於某種原因,Flask 沒有處理文件對象。
我也嘗試在 React Fetch API 調用中添加multi-part/formdata
內容類型,但這也無濟於事。
想通了這個問題。
結果你需要在 React 調用中傳遞[0]
:
data.append("file", file[0])
我試圖僅使用 vanilla JS fetch
調用將圖像文件發布到 Flask,@Anubhav 的回答幫助我意識到我需要使用 FormData,而不僅僅是將文件/blob 作為body
。 如果有人正在尋找一些完整的、有效的示例代碼:
<input type="file" id="fileEl"/>
let formData = new FormData();
formData.append("file", fileEl.files[0]);
let response = await fetch("http://example.com/upload", {
method: "POST",
body: formData,
}).then(r => r.json());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.