我有一个简单的代码片段,用于使用 Python 中的 FastAPI 上传文件
。
@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
contents = await file.read()
print(str(contents)[2:-1])
with open(file.filename, "wb") as buffer:
buffer.write(file.file.read())
return {"filename": file.filename}
我用我的前端 React 应用程序尝试了这个,它工作得很好,除了它不保存我收到的数据。此代码应该获取 csv 文件并将其保存在本地。如您所见,我从文件中打印了 contents
,并且打印的 contents
是正确的,但是当我尝试使用 buffer.write(file. file.read())
,我刚刚创建了文件,但其中没有内容,也就是空的。另请注意,当我打印 contents
时,我得到了字符串形式的 csv 文件。有没有办法解决这个问题,或者我需要处理字符串,将其转换为 csv,然后将此数据写入我创建的文件中?
最佳答案
文件数据一旦读取就无法再次使用。所以,只读一次
关于Python FastAPI 不保存 POST 文件请求的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66888868/