File extension validation
See original GitHub issueIs there a way to validate the file format of an input file as a request? If the fastapi app will only accept incoming requests with files that have extensions .pdf,.docx or .txt, how will I implement this using fastapi? Something similar is used in the laravel framework https://stackoverflow.com/questions/32179164/how-to-validate-a-file-type-in-laravel
Example
from fastapi import FastAPI
app = FastAPI()
@app.post("/upload")
def read_file(input_file: UploadFile = File(..., format=[".txt",".pdf",".docx"])):
return {"filename": "input_file.filename"}
Issue Analytics
- State:
- Created 2 years ago
- Comments:9 (4 by maintainers)
Top Results From Across the Web
File Type Validation while Uploading it using JavaScript
Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the ......
Read more >Validation of file extension before uploading file - Stack Overflow
The validation whether the uploaded file is an image is done in server side only, by checking the magic numbers in the file...
Read more >File Type (extension) Validation with JavaScript - CodexWorld
The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension ...
Read more >Validate file extension - Overview - OutSystems
Validate file extension · A magic number is a number embedded at or near the beginning of a file that indicates its file...
Read more >File Format Identification and Validation - Digital Preservation
File Format Identification and Validation Tools ... A file type often has an associated explicit format specification -- a formal declaration of how....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
You can check the MIME type, which should be more accurate than the file extension (https://fastapi.tiangolo.com/tutorial/request-files/#uploadfile). Example:
Of course, you can wrap this logic in a dependency to reuse it in several endpoints.
Actually, you need to set the content type of the file, not the whole request.
The file tuple parameter can accept a third value which is the content type of the file: https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files