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

    xiaoxiao2022-07-13  155

    同事用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) }

     

    最新回复(0)