fastapi
fastapi copied to clipboard
How to decode the UploadFile when read in async way?
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.
- [ ] After submitting this, I commit to one of:
- Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
- I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
- Implement a Pull Request for a confirmed bug.
Example
from fastapi import FastAPI, UploadFile
@app.post("/uploadfile/")
async def create_upload_file(
file: UploadFile = File(...)
):
contents = await file.read()
return {"contents": contents}
Description
my UploadFile is coded in GBK, bug Fastapi's default is utf8, so when I read the UploadFile ,I got the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
how can I decode the UploadFile in my own way?
Environment
- OS: Windows
- FastAPI Version : 0.45.0
To know the FastAPI version use:
python -c "import fastapi; print(fastapi.__version__)"
- Python version:Python 3.6.3
To know the Python version use:
python --version
Additional context
Was it resolved by any chance?
i happen same problem in fastapi-0.75.2 that i upload .wav file ,
# file 参数类型是 UploadFile
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
result = {
"filename": file.filename,
"content-type": file.content_type,
"read": await file.read()
}
return result
我在 fastapi0.86.0 中用GB2312的文本文件或者二进制文件测试:
content = await file.read()
print(type(content)) # <class 'bytes'>
结果都是bytes, 没有遇到str的情况。我直接用wb+写入后可以正常使用 但是当我开启 vscode 的 type checking on后 会遇到警告:Type "bytes | str" cannot be assigned to type "bytes", "str" is incompatible with "bytes" 🤔