使用Go 使用multipart/form-data 上傳
使用RESTful API 時,您可能會遇到需要將資料與內容一起發布的情況-類型:多部分/表單資料。這通常用於文件上傳,其中包含文字和文件參數的組合。在 Go 中,這可以使用 mime/multipart 套件來完成。這是您遇到的問題的解決方案:
程式碼中的問題是您沒有為多部分/表單資料請求設定正確的 Content-Type 標頭。您應該使用 multipart/form-data;charset=UTF-8,而不是使用 application/json。
這是使用multipart/form-data 進行發布的程式碼的改進版本:
<code class="go">import ( "bytes" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "mime/multipart" ) func NewPost2(url string) ([]byte, error) { // Create a multipart/form-data request body. bodyBuf := &bytes.Buffer{} bodyWriter := multipart.NewWriter(bodyBuf) // Add text parameters to the form data. m := make(map[string]interface{}) m["fileName"] = "good" for k, v := range m { bodyWriter.WriteField(k, v.(string)) } // Add a file parameter to the form data. fileBytes := []byte(Base64ToByte("/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDHooor+wD+Zz//2Q==")) name := "test.jpg" fileWriter, err := bodyWriter.CreateFormFile("image_content", name) if err != nil { return nil, err } _, err = fileWriter.Write(fileBytes) if err != nil { return nil, err } bodyWriter.Close() // Create a new HTTP request with the multipart/form-data body. httpReq, err := http.NewRequest("POST", url, bodyBuf) if err != nil { return nil, err } httpReq.Header.Set("Content-Type", bodyWriter.FormDataContentType()) // Perform the HTTP POST request. client := &http.Client{} resp, err := client.Do(httpReq) if err != nil { return nil, err } // Handle the HTTP POST response. defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := httputil.DumpResponse(resp, true) return nil, fmt.Errorf("[%d %s]%s", resp.StatusCode, resp.Status, string(body)) } // Read the HTTP response body. respData, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } // Return the HTTP response body. return respData, nil }</code>
在此解決方案中,我們使用mime/multipart 套件提供的CreateFormFile 和WriteField 方法建立multipart/form-data 請求內文。然後我們相應地設定 Content-Type 標頭。透過這些更改,您的程式碼應該能夠使用 Content-Type:multipart/form-data 成功 POST 資料。
以上是如何在 Go 中使用「multipart/form-data」進行檔案上傳?的詳細內容。更多資訊請關注PHP中文網其他相關文章!