1. 需要fastapi的服务端提供静态文件:
1
| app.mount("/static", StaticFiles(directory=os.path.join(myapp.env().get_data_path(), 'static')), name="static")
|
其中第一个static是网站访问路径,第二个static是磁盘路径,第三个static是FastApi代码内部引用名称
2. 文件上传处理:
1
2
3
4
5
6
7
8
9
10
11
| async def file_upload(
upfile: UploadFile = File(...)
):
dest_file_path = 'uploaded/userfile.ext'
destination = Path(dest_file_path)
try:
with destination.open("wb") as buffer:
shutil.copyfileobj(upfile.file, buffer)
finally:
upload_file.file.close()
|
3. cors问题
服务端配置cros:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| origins = [
# "*"
"https://localhost"
, "http://localhost"
, "http://localhost:8000"
, "https://www.kumaxiong.com"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
# allow_methods=["DELETE", "GET", "POST", "PUT"],
allow_headers=["*"],
)
|
客户端处理的时候不要with-credentials带上cookie等信息:
参考:https://blog.csdn.net/liyuling52011/article/details/80013725