你想處理一個由用戶上傳的文件,比如你正在建設一個類似Instagram的網站,你需要存儲用戶拍攝的照片。這種需求該如何實現呢?
要使表單能夠上傳文件,首先第一步就是要添加form的`enctype`屬性,`enctype`屬性有如下三種情況:
~~~
application/x-www-form-urlencoded 表示在發送前編碼所有字符(默認)
multipart/form-data 不對字符編碼。在使用包含文件上傳控件的表單時,必須使用該值。
text/plain 空格轉換為 "+" 加號,但不對特殊字符編碼。
~~~
所以,表單的html代碼應該類似于:
~~~
<html>
<head>
<title>上傳文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{{.}}"/>
<input type="submit" value="upload" />
</form>
</body>
</html>
~~~
在服務器端,我們增加一個handlerFunc:
~~~
http.HandleFunc("/upload", upload)
// 處理/upload 邏輯
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //獲取請求的方法
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("upload.gtpl")
t.Execute(w, token)
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
~~~
通過上面的代碼可以看到,處理文件上傳我們需要調用`r.ParseMultipartForm`,里面的參數表示`maxMemory`,調用`ParseMultipartForm`之后,上傳的文件存儲在`maxMemory`大小的內存里面,如果文件大小超過了`maxMemory`,那么剩下的部分將存儲在系統的臨時文件中。我們可以通過`r.FormFile`獲取上面的文件句柄,然后實例中使用了`io.Copy`來存儲文件。
> 獲取其他非文件字段信息的時候就不需要調用`r.ParseForm`,因為在需要的時候Go自動會去調用。而且`ParseMultipartForm`調用一次之后,后面再次調用不會再有效果。
通過上面的實例我們可以看到我們上傳文件主要三步處理:
1. 表單中增加enctype="multipart/form-data"
2. 服務端調用`r.ParseMultipartForm`,把上傳的文件存儲在內存和臨時文件中
3. 使用`r.FormFile`獲取文件句柄,然后對文件進行存儲等處理。
文件handler是multipart.FileHeader,里面存儲了如下結構信息
~~~
type FileHeader struct {
Filename string
Header textproto.MIMEHeader
// contains filtered or unexported fields
}
~~~
我們通過上面的實例代碼打印出來上傳文件的信息如下
[](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/images/4.5.upload2.png?raw=true)
圖4.5 打印文件上傳后服務器端接受的信息
## [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/04.5.md#客戶端上傳文件)客戶端上傳文件
我們上面的例子演示了如何通過表單上傳文件,然后在服務器端處理文件,其實Go支持模擬客戶端表單功能支持文件上傳,詳細用法請看如下示例:
~~~
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
)
func postFile(filename string, targetUrl string) error {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
//關鍵的一步操作
fileWriter, err := bodyWriter.CreateFormFile("uploadfile", 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
}
defer fh.Close()
//iocopy
_, err = io.Copy(fileWriter, fh)
if err != nil {
return err
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
resp, err := http.Post(targetUrl, contentType, bodyBuf)
if err != nil {
return err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
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方法把緩存傳到服務器。
> 如果你還有其他普通字段例如username之類的需要同時寫入,那么可以調用multipart的WriteField方法寫很多其他類似的字段。
- 第一章 Go環境配置
- 1.1 Go安裝
- 1.2 GOPATH 與工作空間
- 1.3 Go 命令
- 1.4 Go開發工具
- 1.5 小結
- 第二章 Go語言基礎
- 2.1 你好,Go
- 2.2 Go基礎
- 2.3 流程和函數
- 2.4 struct類型
- 2.5 面向對象
- 2.6 interface
- 2.7 并發
- 2.8 總結
- 第三章 Web基礎
- 3.1 Web工作方式
- 3.2 Go搭建一個Web服務器
- 3.3 Go如何使得Web工作
- 3.4 Go的http包詳解
- 3.5 小結
- 第四章 表單
- 4.1 處理表單的輸入
- 4.2 驗證表單的輸入
- 4.3 預防跨站腳本
- 4.4 防止多次遞交表單
- 4.5 處理文件上傳
- 4.6 小結
- 第五章 訪問數據庫
- 5.1 database/sql接口
- 5.2 使用MySQL數據庫
- 5.3 使用SQLite數據庫
- 5.4 使用PostgreSQL數據庫
- 5.5 使用beedb庫進行ORM開發
- 5.6 NOSQL數據庫操作
- 5.7 小結
- 第六章 session和數據存儲
- 6.1 session和cookie
- 6.2 Go如何使用session
- 6.3 session存儲
- 6.4 預防session劫持
- 6.5 小結
- 第七章 文本處理
- 7.1 XML處理
- 7.2 JSON處理
- 7.3 正則處理
- 7.4 模板處理
- 7.5 文件操作
- 7.6 字符串處理
- 7.7 小結
- 第八章 Web服務
- 8.1 Socket編程
- 8.2 WebSocket
- 8.3 REST
- 8.4 RPC
- 8.5 小結
- 第九章 安全與加密
- 9.1 預防CSRF攻擊
- 9.2 確保輸入過濾
- 9.3 避免XSS攻擊
- 9.4 避免SQL注入
- 9.5 存儲密碼
- 9.6 加密和解密數據
- 9.7 小結
- 第十章 國際化和本地化
- 10.1 設置默認地區
- 10.2 本地化資源
- 10.3 國際化站點
- 10.4 小結
- 第十一章 錯誤處理,調試和測試
- 11.1 錯誤處理
- 11.2 使用GDB調試
- 11.3 Go怎么寫測試用例
- 11.4 小結
- 第十二章 部署與維護
- 12.1 應用日志
- 12.2 網站錯誤處理
- 12.3 應用部署
- 12.4 備份和恢復
- 12.5 小結
- 第十三章 如何設計一個Web框架
- 13.1 項目規劃
- 13.2 自定義路由器設計
- 13.3 controller設計
- 13.4 日志和配置設計
- 13.5 實現博客的增刪改
- 13.6 小結
- 第十四章 擴展Web框架
- 14.1 靜態文件支持
- 14.2 Session支持
- 14.3 表單及驗證支持
- 14.4 用戶認證
- 14.5 多語言支持
- 14.6 pprof支持
- 14.7 小結
- 附錄A 參考資料