使用net/http和Mux在Golang中接收上傳的檔案
簡介
建置一個處理文件上傳是Web 開發中的常見任務。在Golang中,您可以利用net/http套件來有效管理文件上傳。這是關於如何使用流行的 Mux 路由器在 Golang net/http 伺服器中接收上傳檔案的綜合指南。
實作檔案上傳
要在伺服器中啟用檔案上傳功能,您需要進行下列變更:
建立處理傳入文件上傳請求的端點。此端點應在路由器變數中定義:
router. Path("/upload"). Methods("POST"). HandlerFunc(UploadFile)
在UploadFile函數中,需要解析多部分錶單資料。這是上傳的檔案可用的地方:
func UploadFile(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(5 * 1024 * 1024) if err != nil { panic(err) } // Retrieve the file from the multipart form file, header, err := r.FormFile("fileupload") if err != nil { panic(err) } defer file.Close() // Do something with the uploaded file, such as storing it in a database or processing it }
要處理文件,您可以將其內容讀入緩衝區並根據需要進行處理。這是一個例子:
var buf bytes.Buffer io.Copy(&buf, file) contents := buf.String() fmt.Println(contents)
如果您使用cURL 將檔案作為多部分錶單資料傳送,請確保提供正確的參數:
curl http://localhost:8080/upload -F "fileupload=[email protected]"
依照下列步驟,您可以成功使用 Mux 在 Golang net/http 伺服器中接收上傳的檔案。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3