這個 API 讓使用者可以 上傳本地檔案,並自動讀取裡面的文字內容,不論是 .txt
、.docx
還是 .pdf
,都能解析。
@app.post("/upload-file")
async def upload_file(file: UploadFile = File(...)):
"""
上傳檔案並讀取內容
"""
try:
# 檔案大小限制 10MB
if file.size and file.size > 10 * 1024 * 1024:
raise HTTPException(status_code=400, detail="檔案大小超過 10MB 限制")
# 建立暫存目錄
temp_dir = Path("temp_uploads")
temp_dir.mkdir(exist_ok=True)
# 儲存檔案到暫存
temp_file_path = temp_dir / file.filename
with open(temp_file_path, "wb") as buffer:
content = await file.read()
buffer.write(content)
# 根據檔案類型讀取內容
try:
file_content = get_file_content(str(temp_file_path), file.filename)
if temp_file_path.exists():
temp_file_path.unlink() # 上傳完成後刪除暫存檔案
logger.info(f"成功讀取檔案: {file.filename}")
return {
"status": "success",
"message": f"成功上傳並讀取檔案: {file.filename}",
"content": file_content,
"filename": file.filename
}
except ValueError as e:
if temp_file_path.exists():
temp_file_path.unlink()
raise HTTPException(status_code=400, detail=str(e))
except HTTPException:
raise
except Exception as e:
logger.error(f"上傳檔案時發生錯誤: {e}")
if 'temp_file_path' in locals() and temp_file_path.exists():
temp_file_path.unlink()
raise HTTPException(status_code=500, detail=f"上傳檔案時發生錯誤: {e}")
wb
二進位模式.txt
, .py
, .js
, .html
, .css
, .json
, .xml
, .csv
.docx
/ .doc
.pdf
ValueError
status
:成功或失敗message
:訊息content
:檔案文字內容filename
:檔名