我通过fastAPI创建了一个API,如下所示:
@app.post('/uploadFile/')
async def uploadFile(file:UploadFile = File(...)):
file_name,extension_file_name = os.path.splitext(file.filename)
base_path = os.path.join(os.getcwd(),'static')
path_cheked_exists = os.path.join(base_path,extension_file_name[1:])
if not os.path.exists(path_cheked_exists):
os.makedirs(path_cheked_exists)
try:
shutil.copy(file,path_cheked_exists)
except Exception as exp:
print("can not copy that file")
return {'file':'okay'}
API返回结果但未保存file
.
感谢您对shutil
模块的帮助
您可以使用简单的上下文管理器
而不是使用shutil模块。with open('filename.ext', 'wb+') as file_obj:
file_obj.write(file.file.read())
你的问题也可能是你只写文件。尝试shutil.copy (file.file path_cheked_exists)