上傳 API
最後更新
本頁說明
POST /upload/*path 的請求格式、檔名產生規則與各種回應。請求
- curl -X POST -F "filepath=@./photo.jpg" http://localhost:8080/upload/blog/2025
| 項目 | 規則 |
|---|---|
*path | 目標資料夾,相對於 storage/image/upload/;不存在時自動建立;空值回 400 |
| 表單欄位 | filepath(multipart/form-data) |
| 類型判斷 | 依該 part 的 Content-Type 標頭,不檢查檔案內容 |
| 支援類型 | image/jpeg、image/jpg、image/png、image/webp、image/svg+xml、application/pdf |
| 大小上限 | Go 端無限制;Nginx client_max_body_size 100M |
檔名
上傳檔一律重新命名為
{16 位英數}_{毫秒時間戳}{副檔名},副檔名由 GetExtension 依 MIME 決定(image/jpeg、image/jpg 皆為 .jpg)。隨機字元由 math/rand 產生,程式啟動時以當下時間為 seed。回應
成功回
201:- {
- "success": 1,
- "filename": "ERftP1gTS7WCTeJ8_1744080848530.jpg",
- "type": "image/jpeg",
- "size": 2501808,
- "src": "http://localhost:8080/c/img/blog/2025/ERftP1gTS7WCTeJ8_1744080848530.jpg"
- }
src 的網域由 configs.GetDomain() 決定:GO_ENV=development 時為 http://localhost:{PORT},否則為 https://{DOMAIN}。| 狀態碼 | 內容 | 情境 |
|---|---|---|
400 | please assign a path first | *path 為空 |
400 | can not create folder: ... | 建立資料夾失敗 |
400 | can not get file form request | 缺少 filepath 欄位 |
400 | can not save file | 寫檔失敗 |
201 | filename/type/src 為空字串、size 為該檔大小的 JSON;檔案不會寫入 | 不支援的類型 |
408 | timed out | 超過 30 秒 |
判斷上傳結果
只看
201 不代表檔案已寫入:不支援的類型同樣回 201,但 filename 為空。需同時檢查狀態碼與 filename:- status=$(curl -s -o response.json -w "%{http_code}" \
- -X POST -F "filepath=@./photo.jpg" \
- http://localhost:8080/upload/blog/2025)
- if [ "$status" != "201" ] || [ -z "$(jq -r '.filename // empty' response.json)" ]; then
- echo "upload failed ($status): $(cat response.json)" >&2
- exit 1
- fi
- jq -r '.src' response.json
即使上傳被拒,
storage/image/upload/ 下的目標資料夾也已建立:os.MkdirAll 在讀取表單欄位與檢查類型之前就執行。