iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0

上傳檔案並讀取內容 — 我的 AI 助手 API (7)

這個 API 讓使用者可以 上傳本地檔案,並自動讀取裡面的文字內容,不論是 .txt.docx 還是 .pdf,都能解析。


功能

  • 上傳檔案到伺服器暫存目錄
  • 支援常見文字、程式碼、Word 與 PDF
  • 自動讀取檔案內容
  • 檢查檔案大小(最大 10MB)
  • 解析失敗會回傳明確錯誤訊息

核心程式碼

@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}")


解析流程

  1. 檢查檔案大小:最大 10MB
  2. 建立暫存目錄:保證上傳檔案有地方存放
  3. 寫入暫存檔案:使用 wb 二進位模式
  4. 讀取檔案內容
    • 文字檔:支援 .txt, .py, .js, .html, .css, .json, .xml, .csv
    • Word 檔:.docx / .doc
    • PDF 檔:.pdf
    • 不支援格式會回傳 ValueError
  5. 清理暫存檔案:讀完就刪除
  6. 回傳結果
    • status:成功或失敗
    • message:訊息
    • content:檔案文字內容
    • filename:檔名

上一篇
DAY 11
系列文
我的 AI 助手開發12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言