Go File Upload Handler
Handle multipart file uploads in Go with size limits, MIME type validation, unique filename generation, streaming to disk without buffering entire file, and.
Code
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(10 << 20)
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "No file", http.StatusBadRequest)
return
}
defer file.Close()
dst, _ := os.Create(fmt.Sprintf("uploads/%d-%s", time.Now().Unix(), header.Filename))
defer dst.Close()
io.Copy(dst, file)
fmt.Fprintf(w, `{"path":"%s","size":%d}`, dst.Name(), header.Size)
}