Skip to content

Handling Multipart form data with the full filename set as name in Content-Disposition #2977

@mntolia

Description

@mntolia

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Example

Here's a self-contained, minimal, reproducible, example with my use case:

from typing import List

from fastapi import FastAPI, Request, File, UploadFile

app = FastAPI()


@app.post("/1")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}

Description

I am getting 2 files as form data from an IoT device. One is a XML file and the other is an image file
The issue is that the "name" part of the Content-Disposition is set as "anpr.xml" and "licensePlatePicture.jpg" for each file respectively.
I am not sure how to parse this in FastAPI as I can't set anpr.xml as the variable name for the method.

This is the request header:

Headers({'accept': 'text/html, application/xhtml+xml, */*', 'accept-language': 'zh-CN', 'content-type': 'multipart/form-data;boundary=-------------------------7e13971310878', 'user-agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)', 'accept-encoding': 'gzip, deflate', 'host': '****', 'content-length': '419354', 'connection': 'Keep-Alive', 'cache-control': 'no-cache'})

This is a redacted request body:

---------------------------7e13971310878
Content-Disposition: form-data; name="anpr.xml";filename="anpr.xml";
Content-Type: application/xml; charset="UTF-8"
Content-Length: 2672

<?xml version="1.0" encoding="utf-8"?>
.....
---------------------------7e13971310878
Content-Disposition: form-data;name="licensePlatePicture.jpg";filename="licensePlatePicture.jpg";
Content-Type: image/pjpeg
Content-Length: 2124
......
---------------------------7e13971310878--

How do I process this in FastAPI?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions