无法使用前端中使用JavaScript Fetch API上传到FastApi后端

发布于 2025-01-18 16:29:41 字数 1243 浏览 1 评论 0 原文

我试图弄清楚如何将图像发送到我的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去做不打算做的事情。

I'm trying to figure out how to send an image to my API, and also verify a generated token that is in the header of the request.

So far this is where I'm at:

@app.post("/endreProfilbilde")
async def endreProfilbilde(request: Request,file: UploadFile = File(...)):
    token=request.headers.get('token')
    print(token)
    print(file.filename)

I have another function that triggers the change listener and upload function, passing the parameter: 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
}

The Problem:
This will print the filename of the uploaded file, but the token isn't passed and is printed as None. I suspect this may be due to the content-type, or that I'm trying to force FastAPI to do something that is not meant to be doing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诠释孤独 2025-01-25 16:29:41

根据文档

警告:使用FormData 使用 POST 请求=“不关注” noreferrer">XMLHttpRequestFetch_API
multipart/form-data 内容类型(例如上传文件
Blob 到服务器) ,不要显式设置内容类型
请求的标头。这样做会阻止浏览器
能够使用 boundary 表达式设置 Content-Type 标头
它将用于分隔请求正文中的表单字段。

因此,在发送 fetch 请求时,您应该从代码中删除 Content-Type 标头。这同样适用于通过 Python 请求 发送请求,如此处此处。详细了解 multipart/form-data 中的边界

有关如何在后端使用 FastAPI 和在前端使用 Fetch API 上传文件的工作示例,请参见 这里这里,以及此处此处此处

As per the documentation:

Warning: When using FormData to submit POST requests using XMLHttpRequest or the Fetch_API with the
multipart/form-data Content-Type (e.g. when uploading Files and
Blobs to the server), do not explicitly set the Content-Type
header on the request. Doing so will prevent the browser from being
able to set the Content-Type header with the boundary expression
it will use to delimit form fields in the request body.

Hence, you should remove the Content-Type header from your code when sending the fetch 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.

思念满溢 2025-01-25 16:29:41

感谢 Python 的 Discord 服务器中一位乐于助人的小伙子,我想出了这个办法。

function lastOpp(bildeFila) {
            let data = new FormData();
            data.append('file',bildeFila)
            data.append('token','SOMETOKENINFO')
}
@app.post("/endreProfilbilde")
async def endreProfilbilde(token: str = Form(...),file: UploadFile = File(...)):
    print(file.filename)
    print(token)

将字符串值作为 formData 的一部分而不是作为标头发送,可以让我获取参数。

So I figured this one out thanks to a helpful lad in Python's Discord server.

function lastOpp(bildeFila) {
            let data = new FormData();
            data.append('file',bildeFila)
            data.append('token','SOMETOKENINFO')
}
@app.post("/endreProfilbilde")
async def endreProfilbilde(token: str = Form(...),file: UploadFile = File(...)):
    print(file.filename)
    print(token)

Sending the string value as part of the formData rather than as a header lets me grab the parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文