无法使用前端中使用JavaScript Fetch API上传到FastApi后端
我试图弄清楚如何将图像发送到我的API,并还验证请求的 header
中生成的令牌
。
到目前为止,这就是我所处的位置:
@app.post("/endreProfilbilde")
async def endreProfilbilde(request: Request,file: UploadFile = File(...)):
token=request.headers.get('token')
print(token)
print(file.filename)
我有另一个函数可以触发更改侦听器和上传功能,传递参数: bildefila
function lastOpp(bildeFila) {
var myHeaders = new Headers();
let data = new FormData();
data.append('file',bildeFila)
myHeaders.append('token', 'SOMEDATAHERE');
myHeaders.append('Content-Type','image/*');
let myInit = {
method: 'POST',
headers: myHeaders,
cache: 'default',
body: data,
};
var myRequest = new Request('http://127.0.0.1:8000/endreProfilbilde', myInit);
fetch(myRequest)//more stuff here, but it's irrelevant for the Q
}
问题:
这将打印上传文件的文件名
,但是令牌
未传递,并将其打印为 none
。我怀疑这可能是由于 content-type
,或者我试图强迫fastapi去做不打算做的事情。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据文档:
因此,在发送
fetch
请求时,您应该从代码中删除Content-Type
标头。这同样适用于通过 Python 请求 发送请求,如此处 和 此处。详细了解 multipart/form-data 中的边界。有关如何在后端使用 FastAPI 和在前端使用 Fetch API 上传文件的工作示例,请参见 这里,这里,以及此处、此处和此处。
As per the documentation:
Hence, you should remove the
Content-Type
header from your code when sending thefetch
request. The same applies to sending requests through Python Requests, as described here and here. Read more about the boundary in multipart/form-data.Working examples on how to upload file(s) using FastAPI in the backend and Fetch API in the frontend can be found here, here, as well as here, here and here.
感谢 Python 的 Discord 服务器中一位乐于助人的小伙子,我想出了这个办法。
将字符串值作为 formData 的一部分而不是作为标头发送,可以让我获取参数。
So I figured this one out thanks to a helpful lad in Python's Discord server.
Sending the string value as part of the formData rather than as a header lets me grab the parameter.