首页  >  文章  >  后端开发  >  鉴于我之前的尝试导致了 301 Moved Pe,如何在 Go 中发送 Content-Type: multipart/form-data 的 POST 请求,同时包含 []byte 参数和字符串参数

鉴于我之前的尝试导致了 301 Moved Pe,如何在 Go 中发送 Content-Type: multipart/form-data 的 POST 请求,同时包含 []byte 参数和字符串参数

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 06:51:02314浏览

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?

我可以使用 Content-Type: multipart/form-data 发帖吗?

问题:

如何发送内容类型为 multipart/form-data 的 POST 请求,同时包含 []byte 参数和字符串参数?之前的尝试导致了以下错误:

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

提供的 Go 代码:

<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>

答案:

提供的代码尝试在请求正文中以 JSON 形式发送 []byte 参数,这不是 multipart/form-data 提交的合适格式。

要纠正此问题,我们可以使用 multipart/form-使用以下更新代码进行数据编码:

<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>

通过使用 multipart/form-data 编码并正确处理文件参数,我们现在可以使用 []byte 参数和字符串参数成功 POST。

以上是鉴于我之前的尝试导致了 301 Moved Pe,如何在 Go 中发送 Content-Type: multipart/form-data 的 POST 请求,同时包含 []byte 参数和字符串参数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn