Home  >  Article  >  Backend Development  >  How can I send a POST request with Content-Type: multipart/form-data in Go, while including both []byte parameters and string arguments, given that my previous attempts have resulted in a 301 Moved Pe

How can I send a POST request with Content-Type: multipart/form-data in Go, while including both []byte parameters and string arguments, given that my previous attempts have resulted in a 301 Moved Pe

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 06:51:02203browse

How can I send a POST request with Content-Type: multipart/form-data in Go, while including both []byte parameters and string arguments, given that my previous attempts have resulted in a 301 Moved Permanently error?

Can I post with Content-Type: multipart/form-data?

Question:

How can I send a POST request with Content-Type: multipart/form-data while including both []byte parameters and string arguments? Previous attempts have resulted in the following error:

[301 301 Moved Permanently]<...HTML response body...>

Provided Go Code:

<code class="go">func NewPost2(url string) ([]byte, error) {
    m := make(map[string]interface{}, 0)
    m["fileName"] ="good"
    m["name"] = Base64ToByte("/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDHooor+wD+Zz//2Q==")
    b, _ := json.Marshal(m)

    httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
    httpReq.Header.Set("Content-Type", "multipart/form-data;charset=UTF-8")

    client := &amp;http.Client{}
    resp, err := client.Do(httpReq)
    if err != nil {
        return nil, err
    }

    defer resp.Body.Close()

    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        b, _ := ioutil.ReadAll(resp.Body)
        return nil, fmt.Errorf("[%d %s]%s", resp.StatusCode, resp.Status, string(b))
    }

    respData, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    return respData, nil
}</code>

Answer:

The provided code attempted to send []byte parameters as JSON in the request body, which is not an appropriate format for multipart/form-data submissions.

To correct this issue, we can use multipart/form-data encoding with the following updated code:

<code class="go">func NewPostFile(url string, paramTexts map[string]interface{}, paramFile FileItem) ([]byte, error) {
// if paramFiles ==nil {
//  return NewPost(url,paramTexts,header,transport)
// }

// Create a new multipart writer
bodyBuf := &amp;bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)

// Write text parameters to the multipart writer
for k, v := range paramTexts {
    bodyWriter.WriteField(k, v.(string))
}

// Write the file content to the multipart writer
fileWriter, err := bodyWriter.CreateFormFile(paramFile.Key, paramFile.FileName)
if err != nil {
    fmt.Println(err)
    //fmt.Println("Create form file error: ", error)
    return nil, err
}
fileWriter.Write(paramFile.Content)

// Close the multipart writer
bodyWriter.Close()

// Set the Content-Type header to multipart/form-data
contentType := bodyWriter.FormDataContentType()

// Create the POST request with the multipart/form-data body
resp, err := http.Post(url, contentType, bodyBuf)
if err != nil {
    return nil, err
}

// Handle and process the HTTP response
// ... (remainder of code omitted for brevity)</code>

By using multipart/form-data encoding and correctly handling the file parameters, we can now successfully POST with []byte parameters and string arguments.

The above is the detailed content of How can I send a POST request with Content-Type: multipart/form-data in Go, while including both []byte parameters and string arguments, given that my previous attempts have resulted in a 301 Moved Pe. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn