dropbox1111 2017-06-01 00:30
浏览 276
已采纳

我可以在Go中发布Content-Type:multipart / form-data吗?

How do I POST to an API with Content-Type: multipart/form-data, []byte parameters and string arguments? I have tried, but it is failing.

Error message:

details: "[301 301 Moved Permanently]<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html>
301 Moved Permanently
<body bgcolor=\"white\">
301 Moved Permanently
<p>The requested resource has been assigned a new permanent URI.</p >
<hr/>Powered by Tengine/2.1.0</body>
</html>
"

Go code:

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 := &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
}

展开全部

  • 写回答

2条回答 默认 最新

  • dongsi073898 2017-06-01 03:22
    关注

    Now, I am very happy with the mood to share my solution

    func NewPostFile(url string, paramTexts map[string]interface{}, paramFile FileItem) ([]byte, error) {
    // if paramFiles ==nil {
    //  return NewPost(url,paramTexts,header,transport)
    // }
    
    bodyBuf := &bytes.Buffer{}
    bodyWriter := multipart.NewWriter(bodyBuf)
    
    for k, v := range paramTexts {
        bodyWriter.WriteField(k, v.(string))
    }
    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)
    contentType := bodyWriter.FormDataContentType()
    bodyWriter.Close()
    fmt.Println(bodyBuf.String())
    
    resp, err := http.Post(url, contentType, bodyBuf)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    fmt.Println(resp)
    
    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
    }
    fmt.Println(string(respData))
    return respData, nil
    

    }

    type FileItem struct {
    Key      string //image_content
    FileName string //test.jpg
    Content  []byte //[]byte
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:treenode反序列化后获取不到上一节点和下一节点,Fullpath和Handle报错
  • ¥15 一部手机能否同时用不同的app进入不同的直播间?
  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing