使用 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中文网其他相关文章!