<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                {% raw %} # 4.5 處理文件上傳 你想處理一個由用戶上傳的文件,比如你正在建設一個類似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 } 我們通過上面的實例代碼打印出來上傳文件的信息如下 ![](images/4.5.upload2.png?raw=true) 圖4.5 打印文件上傳后服務器端接受的信息 ## 客戶端上傳文件 我們上面的例子演示了如何通過表單上傳文件,然后在服務器端處理文件,其實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方法寫很多其他類似的字段。 ## links * [目錄](<preface.md>) * 上一節: [防止多次遞交表單](<04.4.md>) * 下一節: [小結](<04.6.md>) {% endraw %}
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看