golang post文件时Content-Type问题及解决方法

在尝试使用Go语言调用一个要求Content-Type为text/plain的PHP接口时,遇到文件类型错误的问题。Go的multipart包默认设置文件Content-Type为application/octet-stream。通过查看源码找到原因后,提供了两种解决方案:一是修改CreateFormFile源码,二是自定义创建部分并设置Content-Type为text/plain。后者避免了对Go库的修改,实现了接口调用的成功。
摘要由CSDN通过智能技术生成

同事用php写了一个接口,要上传文件,让我做下测试,直接用curl命令调用成功,然后想用golang写个示例,源码如下:

package main

import (

    "bytes"

    "fmt"

    "io/ioutil"

    "mime/multipart"

    "net/http"

)



func main() {

    uri := "http://xxxxxxxxxxxx/api/fileattr" //URL地址 xxxxxxxxxxxx由商务提供

    name := "xxxxxxxxxxxx" //用户名

    pass := "xxxxxxxxxxxx" //密码

    fn := "xxxxxxxxxxxx.txt" //文件路径

    //读出文本文件数据

    file_data, _ := ioutil.ReadFile(fn)

    body := new(bytes.Buffer)

    w := multipart.NewWriter(body)

    //取出内容类型

    content_type := w.FormDataContentType()

    //将文件数据写入

    pa, _ := w.CreateFormFile("file", fn)

    pa.Write(file_data)

    //设置用户名密码

    w.WriteField("name", name)

    w.WriteField("pass", pass)

    w.Close()

    //开始提交

    req, _ := http.NewRequest("POST", uri, body)

    req.Header.Set("Content-Type", content_type)

    resp, _ := http.DefaultClient.Do(req)

    data, _ := ioutil.ReadAll(resp.Body)

    resp.Body.Close()

    fmt.Println(resp.StatusCode)

    fmt.Printf("%s", data)

}

发现总是调用失败,返回文件类型不对,询问后得知,同事做了判断,文件只能为text/plain类型,抓包发现,我提交时的文件类型为:application/octet-stream,仔细查看golang源码:mime/multipart/write.go,CreateFormFile的源码是这样的:

func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error) {

    h := make(textproto.MIMEHeader)

    h.Set("Content-Disposition",

        fmt.Sprintf(`form-data; name="%s"; filename="%s"`,

            escapeQuotes(fieldname), escapeQuotes(filename)))

    h.Set("Content-Type", "application/octet-stream")

    return w.CreatePart(h)

}

可以得知Content-Type被固定为了application/octet-stream,知道原因了,问题就好解决了。

第一种就是直接修改CreateFormFile,或者加个CreateFormFile2命令,这种方法将来golang升级后可能会出问题。

第二种方法可以自己来CreatePart:

h := make(textproto.MIMEHeader)

    h.Set("Content-Disposition",

        fmt.Sprintf(`form-data; name="%s"; filename="%s"`,

            escapeQuotes(fieldname), escapeQuotes(filename)))

    h.Set("Content-Type", "text/plain")

再用 w.CreatePart(h)得到io.Writer,问题解决!这种方法不侵入golang源代码,最终代码如下:

package main
 
import (
    "bytes"
    "fmt"
    "io/ioutil"
    "mime/multipart"
    "net/http"
    "net/textproto"
)
 
func main() {
    uri := "http://xxxxxxxxxxxx/api/fileattr" //URL地址 xxxxxxxxxxxx由商务提供
    name := "xxxxxxxxxx"                      //用户名
    pass := "xxxxxxx"                         //密码
    fn := "x:/xxx/xxx.txt"                    //文件路径
 
    //读出文本文件数据
    file_data, _ := ioutil.ReadFile(fn)
 
    body := new(bytes.Buffer)
    w := multipart.NewWriter(body)
 
    //取出内容类型
    content_type := w.FormDataContentType()
 
    //将文件数据写入
    h := make(textproto.MIMEHeader)
    h.Set("Content-Disposition",
        fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
            "file", //参数名为file
            fn))
    h.Set("Content-Type", "text/plain") //设置文件格式
    pa, _ := w.CreatePart(h)
    pa.Write(file_data)
 
    //设置用户名密码
    w.WriteField("name", name)
    w.WriteField("pass", pass)
 
    w.Close()
 
    //开始提交
    req, _ := http.NewRequest("POST", uri, body)
    req.Header.Set("Content-Type", content_type)
    resp, _ := http.DefaultClient.Do(req)
    data, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    fmt.Println(resp.StatusCode)
    fmt.Printf("%s", data)
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值