// FormFile returns the first file for the provided form key.// FormFile calls ParseMultipartForm and ParseForm if necessary.func(r *Request)FormFile(key string)(multipart.File,*multipart.FileHeader,error){if r.MultipartForm == multipartByReader {returnnil,nil, errors.New("http: multipart handled by MultipartReader")}if r.MultipartForm ==nil{
err := r.ParseMultipartForm(defaultMaxMemory)if err !=nil{returnnil,nil, err
}}if r.MultipartForm !=nil&& r.MultipartForm.File !=nil{if fhs := r.MultipartForm.File[key];len(fhs)>0{
f, err := fhs[0].Open()return f, fhs[0], err
}}returnnil,nil, ErrMissingFile
}
multipart.File是文件对象
// File is an interface to access the file part of a multipart message.// Its contents may be either stored in memory or on disk.// If stored on disk, the File's underlying concrete type will be an *os.File.type File interface{
io.Reader
io.ReaderAt
io.Seeker
io.Closer
}
封装了文件的基本信息
// A FileHeader describes a file part of a multipart request.type FileHeader struct{
Filename string//文件名
Header textproto.MIMEHeader //MIME信息
Size int64//文件大小,单位bit
content []byte//文件内容,类型[]byte
tmpfile string//临时文件}
服务器端编写代码如下
获取客户端传递后的文件流,把文件保存到服务器即可
package main
import("net/http""fmt""html/template""io/ioutil")/*
显示欢迎页upload.html
*/funcwelcome(rw http.ResponseWriter, r *http.Request){
t,_:= template.ParseFiles("template/html/upload.html")
t.Execute(rw,nil)}/*
文件上传
*/funcupload(rw http.ResponseWriter, r *http.Request){//获取普通表单数据
username := r.FormValue("username")
fmt.Println(username)//获取文件流,第三个返回值是错误对象
file, header,_:= r.FormFile("photo")//读取文件流为[]byte
b,_:= ioutil.ReadAll(file)//把文件保存到指定位置
ioutil.WriteFile("D:/new.png", b,0777)//输出上传时文件名
fmt.Println("上传文件名:", header.Filename)}funcmain(){
server := http.Server{Addr:"localhost:8899"}
http.HandleFunc("/", welcome)
http.HandleFunc("/upload", upload)
server.ListenAndServe()}