使用Golang net/http服务器接收上传的文件非常简单,只需要在服务器端定义一个处理函数,该函数将接收到的文件保存到服务器上的指定位置即可。
以下是一个示例:
// 定义处理函数
func uploadFile(w http.ResponseWriter, r *http.Request) {
// 解析请求
r.ParseMultipartForm(32 << 20)
// 获取文件句柄
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// 保存文件
f, err := os.OpenFile("./upload/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
// 将处理函数注册到http服务器
http.HandleFunc("/upload", uploadFile)
// 启动http服务器
http.ListenAndServe(":8080", nil)