我正在做這個角度教程。我正在嘗試使用 python fastAPI 創建一個后端端點,該端點通過 HttpClient POST 接收資料,但我正在努力這樣做。(角度 13.0.2,python 3.7,fastapi 0.70.0)
html模板代碼:
<input type="file" (change)="onFileSelected($event)" #fileUpload>
<div >
{{fileName || "No file uploaded yet."}}
<button mat-mini-fab color="primary" (click)="fileUpload.click()">
<mat-icon>attach_file</mat-icon>
</button>
</div>
對應組件ts代碼:
onFileSelected(event) {
const file: File = event.target.files[0]
console.log(`onFileSelected(${file.name})`)
if (file) {
this.fileName = file.name;
const formData = new FormData();
formData.append("thumbnail", file);
const upload$ = this.http.post("http://localhost:8000/thumbnail-upload", formData);
upload$.subscribe();
console.log("upload done?")
}
fastapi代碼:由inpired此
@app.post("/thumbnail-upload")
def create_file(file: UploadFile = File(...)):
print(file)
return {"file_size": len(file)}
似乎正在進行一些正常的溝通,但我被困在這里:
來自 uvicorn 服務器的輸出:
←[32mINFO←[0m: 127.0.0.1:18231 - "←[1mPOST /thumbnail-upload HTTP/1.1←[0m" ←[31m422 Unprocessable Entity←[0m
瀏覽器除錯控制臺中的輸出:
zone.js:2863 POST http://localhost:8000/thumbnail-upload 422 (Unprocessable Entity)
core.mjs:6495 ERROR HttpErrorResponse {headers: HttpHeaders, status: 422, statusText: 'Unprocessable Entity', url: 'http://localhost:8000/thumbnail-upload', ok: false, …}
我需要如何實作 fastAPI 端點才能運行它?免責宣告:我對 angular/fastapi 很陌生,如果我忘記包含必要的資訊,請。告訴我缺少什么;)
uj5u.com熱心網友回復:
422 錯誤訊息的正文將準確地告訴您缺少哪個欄位。從您的代碼看來,您正在以該thumbnail名稱提交檔案,但您file在 FastAPI 路由中使用了該名稱。由于這兩者不匹配,FastAPI 找不到您假設存在的檔案。將表單引數file重命名為或將 FastAPI 引數重命名為thumbnail:
@app.post("/thumbnail-upload")
def create_file(thumbnail: UploadFile = File(...)):
print(thumbnail)
return {"file_size": len(thumbnail.file.read())}
該UploadFile物件還公開file與幕后的假脫機檔案進行互動。由于它沒有直接給你位元組,我認為呼叫len它不會做你期望它做的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362686.html
