代码展现,如何使用golang 自带net/http,将Form表单中提交上来的文件,指定位置保存。html
ReadHtmlFile OutHtml(html网页,表单测试代码使用)golang
SaveFile (处理提交文件)post
package main import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" ) //读取html文件 func ReadHtmlFile(filePath string) ([]byte, error) { file, err := os.Open(filePath) if err != nil { log.Println("open file err is ", err) return nil, err } htmlByte, err := ioutil.ReadAll(file) if err != nil { log.Println("pase html err is ", err) return nil, err } return htmlByte, err } //将html文件输出 func OutHtml(htmlbytes []byte) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(htmlbytes) }) } //将post接收到的文件,保存到指定目录中 func SaveFile(toFile string) http.Handler { //tofile 指定保存目录 return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { file, _, err := r.FormFile("attachment") //从 form中,接收提交来的文件 if err != nil { log.Println(err) return } //log.Println(file) defer file.Close() f, err := os.OpenFile(toFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) //若是文件不存在,则建立 if err != nil { log.Println(err) return } defer f.Close() _, err = io.Copy(f, file) //将post提交上来的文件,重定向到f中 if err != nil { log.Println(err) } } }) } func main() { htmlbyte, err := ReadHtmlFile("D:\\VsCodeProject\\NetHttpGo\\src\\static\\index.html") if err != nil { log.Println(err) } outhtml := OutHtml(htmlbyte) saveFile := SaveFile("D:\\VsCodeProject\\NetHttpGo\\src\\a.jpg") http.Handle("/", outhtml) http.Handle("/file", saveFile) fmt.Println("listening........") http.ListenAndServe(":8081", nil) }