When attempting to implement a simple file upload endpoint in Golang using Mux and net/http, retrieving the file data from the request body can pose a challenge. The following solution addresses this issue:
import ( "bytes" "fmt" "io" "net/http" "strings" ) func ReceiveFile(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(32 << 20) // limit your max input length! var buf bytes.Buffer file, header, err := r.FormFile("file") // replace "file" with the expected form field name if err != nil { panic(err) } defer file.Close() name := strings.Split(header.Filename, ".") fmt.Printf("File name %s\n", name[0]) io.Copy(&buf, file) contents := buf.String() fmt.Println(contents) buf.Reset() return }
This function:
The above is the detailed content of How to Handle File Uploads in a Golang net/http Server?. For more information, please follow other related articles on the PHP Chinese website!