增加支持客户端上传文件
This commit is contained in:
63
4.5.md
63
4.5.md
@@ -78,8 +78,71 @@
|
||||

|
||||
|
||||
|
||||
##客户端上传文件
|
||||
|
||||
我们上面的例子演示了如何通过表单上传文件,然后在服务器端处理文件,其实Go支持模拟客户端表单功能支持文件上传,详细例子请看如下示例:
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func postFile(filename string, targetUrl string) error {
|
||||
bodyBuf := bytes.NewBufferString("")
|
||||
bodyWriter := multipart.NewWriter(bodyBuf)
|
||||
|
||||
//关键的一步操作
|
||||
fileWriter, err := bodyWriter.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
fmt.Println("error writing to buffer")
|
||||
return err
|
||||
}
|
||||
|
||||
//打开文件句柄操作
|
||||
fh, err := os.Open(filename)
|
||||
if err != nil {
|
||||
fmt.Println("error opening file")
|
||||
return err
|
||||
}
|
||||
|
||||
//iocopy
|
||||
io.Copy(fileWriter, fh)
|
||||
|
||||
contentType := bodyWriter.FormDataContentType()
|
||||
bodyWriter.Close()
|
||||
|
||||
resp, err := http.Post(targetUrl, contentType, bodyBuf)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
resp_body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
fmt.Println(resp.Status)
|
||||
fmt.Println(string(resp_body))
|
||||
return nil
|
||||
}
|
||||
|
||||
// sample usage
|
||||
func main() {
|
||||
target_url := "http://localhost:9090/upload"
|
||||
filename := "./astaxie.pdf"
|
||||
postFile(filename, target_url)
|
||||
}
|
||||
|
||||
|
||||
上面的例子详细展示了如何上传一个文件,客户端上传文件通过multipart的Write把文件信息写入缓存,然后调用http的post方法上传文件。
|
||||
|
||||
>如果你还有其他字段需要同时写入,那么可以调用multipart的WriteField方法写很多其他类似的字段。
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
|
||||
Reference in New Issue
Block a user