1

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.

Chris
  • 4,940
  • 2
  • 7
  • 28
groeterud
  • 97
  • 6

2 Answers2

1

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. The same applies to sending requests through Python Requests, as described here and here. Read more about the boundary in multipart/form-data.

Chris
  • 4,940
  • 2
  • 7
  • 28
  • You are indeed correct, it simply either ignores it or throws and error, as I figured out. I'll be posting my working soluition shorly – groeterud Apr 01 '22 at 17:58
-1

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.

groeterud
  • 97
  • 6