本文介绍了我可以在Go中发布Content-Type:multipart / form-data吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Content-Type发布到一个API:multipart / form-data,[]字节参数和字符串参数?

错误消息:

  details:[301 301永久移动]<!DOCTYPE HTML PUBLIC \ -  // IETF // DTD HTML 2.0 // EN \> \r\\\
< html> \r\ n301永久移动\r \\\
< body bgcolor = \white \> \r\\\
301永久移动\r \\\
< p>请求的资源已被分配新的永久URI。 < / p> \r\\\
< hr />由Tengine / 2.1.0驱动< / body> \r\\\
< / html> \r\\\

前往代码:

  func NewPost2(url string)([] byte,error){
m:= make(map [string] interface {},0)
m [fileName] =good
m [ 名称] = Base64ToByte(/ 9J / 4AAQSkZJRgABAQEAeAB4AAD / 2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz / 2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz / wAARCAABAAEDAS IAAhEBAxEB / 8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL / 8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4 + Tl5ufo6erx8vP09fb3 + PN6 / 8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL / 8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3 + PN6 / 9oADAMBAAIRAxEAPwDHooor + WD + ZZ // 2Q ==)
B,_:= json.Marshal(米)

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无,错误
}

推迟resp.Body.Clos e()

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
}


解决方案

现在,我对分享我的解决方案的心情非常满意

  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.Prin tln(err)
//fmt.Println(\"创建表单文件错误:,错误)
返回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

}


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\">\r\n<html>\r\n301 Moved Permanently\r\n<body bgcolor=\"white\">\r\n301 Moved Permanently\r\n<p>The requested resource has been assigned a new permanent URI.</p >\r\n<hr/>Powered by Tengine/2.1.0</body>\r\n</html>\r\n"

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
}
解决方案

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

}

这篇关于我可以在Go中发布Content-Type:multipart / form-data吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 17:34