基于Go語言實(shí)現(xiàn)文件上傳服務(wù)的示例代碼
引言
在 Web 開發(fā)中,文件上傳 是常見需求,例如頭像上傳、文檔存儲(chǔ)、圖片分享等功能。Go 語言的標(biāo)準(zhǔn)庫 net/http
已經(jīng)內(nèi)置了對(duì) multipart/form-data
類型的支持,能讓我們輕松構(gòu)建一個(gè)文件上傳服務(wù)。
本文將帶你實(shí)現(xiàn)一個(gè)可運(yùn)行的文件上傳接口,并附帶 HTML 表單和 curl
測試方法。
一、目標(biāo)功能
路徑:/upload
方法:POST
表單字段:
file
:上傳文件desc
:文件描述(可選)
保存文件到本地 ./uploads
目錄
返回 JSON 結(jié)果
二、核心知識(shí)點(diǎn)
r.ParseMultipartForm(maxMemory)
:解析multipart/form-data
表單r.FormFile("file")
:獲取上傳的文件io.Copy(dst, src)
:保存文件到本地- 表單字段獲取:
r.FormValue("desc")
- 文件權(quán)限控制:
os.Create()
/os.MkdirAll()
三、完整代碼
package main import ( "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" ) type UploadResponse struct { Filename string `json:"filename"` Size int64 `json:"size"` Desc string `json:"desc"` Status string `json:"status"` } func uploadHandler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) return } // 解析上傳表單(maxMemory 5MB,超過部分存臨時(shí)文件) err := r.ParseMultipartForm(5 << 20) if err != nil { http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest) return } // 獲取表單字段 desc := r.FormValue("desc") // 獲取文件 file, handler, err := r.FormFile("file") if err != nil { http.Error(w, "Error retrieving file: "+err.Error(), http.StatusBadRequest) return } defer file.Close() // 確保保存目錄存在 os.MkdirAll("./uploads", os.ModePerm) // 保存文件 filePath := filepath.Join("uploads", handler.Filename) dst, err := os.Create(filePath) if err != nil { http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError) return } defer dst.Close() size, err := io.Copy(dst, file) if err != nil { http.Error(w, "Error writing file: "+err.Error(), http.StatusInternalServerError) return } // 返回 JSON 響應(yīng) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(UploadResponse{ Filename: handler.Filename, Size: size, Desc: desc, Status: "success", }) } func main() { http.HandleFunc("/upload", uploadHandler) fmt.Println("文件上傳服務(wù)已啟動(dòng):http://localhost:8080/upload") http.ListenAndServe(":8080", nil) }
四、測試方法
1. HTML 表單測試
保存為 upload.html
:
<!DOCTYPE html> <html> <body> <h2>文件上傳測試</h2> <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data"> 文件描述: <input type="text" name="desc"> 選擇文件: <input type="file" name="file"> <input type="submit" value="上傳"> </form> </body> </html>
打開瀏覽器選擇文件并提交。
2. curl 命令測試
curl -X POST http://localhost:8080/upload \ -F "desc=測試圖片" \ -F "file=@test.png"
五、運(yùn)行效果
成功上傳后返回:
{ "filename": "test.png", "size": 15324, "desc": "測試圖片", "status": "success" }
文件會(huì)保存在 ./uploads/test.png
。
六、注意事項(xiàng)
上傳限制: 通過 r.ParseMultipartForm(maxMemory)
控制內(nèi)存占用,超過部分會(huì)寫入臨時(shí)文件。
安全性:
- 校驗(yàn)文件類型(避免執(zhí)行惡意文件)
- 生成唯一文件名(避免覆蓋)
- 設(shè)置合理的文件大小限制(可用
http.MaxBytesReader
)
跨域請(qǐng)求: 如果前端與后端不在同一域名,需要設(shè)置 Access-Control-Allow-Origin
等 CORS 頭。
七、進(jìn)階擴(kuò)展
- 上傳時(shí)自動(dòng)生成文件唯一 ID(防止文件名沖突)
- 返回文件訪問 URL
- 將文件上傳到云存儲(chǔ)(如 AWS S3、阿里云 OSS)
- 支持多文件同時(shí)上傳(
r.MultipartForm.File["file"]
)
到此這篇關(guān)于基于Go語言實(shí)現(xiàn)文件上傳服務(wù)的示例代碼的文章就介紹到這了,更多相關(guān)Go文件上傳服務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang格式化輸出函數(shù)printf、sprintf、fprintf解讀
這篇文章主要介紹了golang格式化輸出函數(shù)printf、sprintf、fprintf,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-07-07Go調(diào)度器學(xué)習(xí)之系統(tǒng)調(diào)用詳解
這篇文章腫,將以一個(gè)簡單的文件打開的系統(tǒng)調(diào)用,來分析一下Go調(diào)度器在系統(tǒng)調(diào)用時(shí)做了什么。文中的示例代碼講解詳細(xì),需要的可以參考一下2023-04-04從Context到go設(shè)計(jì)理念輕松上手教程
這篇文章主要為大家介紹了從Context到go設(shè)計(jì)理念輕松上手教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09一文帶你了解Go中跟蹤函數(shù)調(diào)用鏈的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了go如何實(shí)現(xiàn)一個(gè)自動(dòng)注入跟蹤代碼,并輸出有層次感的函數(shù)調(diào)用鏈跟蹤命令行工具,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11Golang官方限流器time/rate的使用與實(shí)現(xiàn)詳解
限流器是后臺(tái)服務(wù)中十分重要的組件,在實(shí)際的業(yè)務(wù)場景中使用居多。time/rate?包基于令牌桶算法實(shí)現(xiàn)限流,本文主要為大家介紹了time/rate的使用與實(shí)現(xiàn),需要的可以參考一下2023-04-04