Skip to content

Commit 7246f9b

Browse files
committed
增加支持客户端上传文件
1 parent fd4bd82 commit 7246f9b

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

4.5.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,71 @@
7878
![](images/4.5.upload2.png?raw=true)
7979

8080

81+
##客户端上传文件
82+
83+
我们上面的例子演示了如何通过表单上传文件,然后在服务器端处理文件,其实Go支持模拟客户端表单功能支持文件上传,详细例子请看如下示例:
84+
85+
package main
86+
87+
import (
88+
"bytes"
89+
"fmt"
90+
"io"
91+
"io/ioutil"
92+
"mime/multipart"
93+
"net/http"
94+
"os"
95+
)
96+
97+
func postFile(filename string, targetUrl string) error {
98+
bodyBuf := bytes.NewBufferString("")
99+
bodyWriter := multipart.NewWriter(bodyBuf)
100+
101+
//关键的一步操作
102+
fileWriter, err := bodyWriter.CreateFormFile("file", filename)
103+
if err != nil {
104+
fmt.Println("error writing to buffer")
105+
return err
106+
}
107+
108+
//打开文件句柄操作
109+
fh, err := os.Open(filename)
110+
if err != nil {
111+
fmt.Println("error opening file")
112+
return err
113+
}
114+
115+
//iocopy
116+
io.Copy(fileWriter, fh)
117+
118+
contentType := bodyWriter.FormDataContentType()
119+
bodyWriter.Close()
120+
121+
resp, err := http.Post(targetUrl, contentType, bodyBuf)
122+
if err != nil {
123+
panic(err.Error())
124+
}
125+
defer resp.Body.Close()
126+
resp_body, err := ioutil.ReadAll(resp.Body)
127+
if err != nil {
128+
panic(err.Error())
129+
}
130+
fmt.Println(resp.Status)
131+
fmt.Println(string(resp_body))
132+
return nil
133+
}
134+
135+
// sample usage
136+
func main() {
137+
target_url := "http://localhost:9090/upload"
138+
filename := "./astaxie.pdf"
139+
postFile(filename, target_url)
140+
}
141+
81142

143+
上面的例子详细展示了如何上传一个文件,客户端上传文件通过multipart的Write把文件信息写入缓存,然后调用http的post方法上传文件。
82144

145+
>如果你还有其他字段需要同时写入,那么可以调用multipart的WriteField方法写很多其他类似的字段。
83146
84147
## links
85148
* [目录](<preface.md>)

0 commit comments

Comments
 (0)