Uploading with multipart/form-data Using Go
When working with RESTful APIs, you may encounter the need to post data with the Content-Type: multipart/form-data. This is commonly used for file uploads, where you have a combination of text and file parameters. In Go, this can be done using the mime/multipart package. Here's a solution to the issue you faced:
The issue in your code was that you were not setting the correct Content-Type header for multipart/form-data requests. Instead of using application/json, you should use multipart/form-data;charset=UTF-8.
Here's an improved version of your code that uses multipart/form-data for posting:
<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>
In this solution, we are creating a multipart/form-data request body using the CreateFormFile and WriteField methods provided by the mime/multipart package. We are then setting the Content-Type header accordingly. With these changes, your code should be able to successfully POST data with Content-Type: multipart/form-data.
The above is the detailed content of How to Use `multipart/form-data` for File Uploads in Go?. For more information, please follow other related articles on the PHP Chinese website!