濮阳杆衣贸易有限公司

主頁 > 知識庫 > 解決golang post文件時Content-Type出現(xiàn)的問題

解決golang post文件時Content-Type出現(xiàn)的問題

熱門標簽:評價高的400電話辦理 外呼系統(tǒng)用什么卡 百度地圖標注后傳給手機 電話機器人軟件免費 外呼系統(tǒng)顯本地手機號 壽光微信地圖標注 阿克蘇地圖標注 excel地圖標注分布數(shù)據(jù) 涿州代理外呼系統(tǒng)

同事用php寫了一個接口,要上傳文件,讓我做下測試,直接用curl命令調(diào)用成功,然后想用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" //文件路徑
 
    //讀出文本文件數(shù)據(jù) 
    file_data, _ := ioutil.ReadFile(fn) 
    body := new(bytes.Buffer) 
    w := multipart.NewWriter(body)
 
    //取出內(nèi)容類型 
    content_type := w.FormDataContentType() 
    //將文件數(shù)據(jù)寫入 
    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) 
}

發(fā)現(xiàn)總是調(diào)用失敗,返回文件類型不對,詢問后得知,同事做了判斷,文件只能為text/plain類型,抓包發(fā)現(xiàn),我提交時的文件類型為: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"                    //文件路徑
 
    //讀出文本文件數(shù)據(jù)
    file_data, _ := ioutil.ReadFile(fn)
 
    body := new(bytes.Buffer)
    w := multipart.NewWriter(body)
 
    //取出內(nèi)容類型
    content_type := w.FormDataContentType()
 
    //將文件數(shù)據(jù)寫入
    h := make(textproto.MIMEHeader)
    h.Set("Content-Disposition",
        fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
            "file", //參數(shù)名為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)
}

補充:用go來玩最簡單的web服務器------順便說說Content-Type字段

web服務端代碼s.go:

package main 
import (
    "io"
    "log"
    "net/http"
)
 
func handlerHello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello girls")
}
 
func main() {
    http.HandleFunc("/hello", handlerHello)     // 注冊   
    err := http.ListenAndServe("localhost:8080", nil)
    if err != nil {
        log.Println(err)
    }
}

go run s.go一下,跑起來, 然后在瀏覽器執(zhí)行http://127.0.0.1:8080/hello (或者在命令行用curl發(fā)http請求也可以), 瀏覽器上的結果為:

hello girls

好簡單??梢栽诳蛻舳嘶蛘叻斩俗グ聪?, 很典型的http req和rsp.

我們再來看一個有趣的問題, 修改s.go為:

package main 
import (
    "io"
    "log"
    "net/http"
)
 
func handlerHello(w http.ResponseWriter, r *http.Request) {
    str := `
        table border="1">
        tr>
        td>row 1, cell 1/td>
        td>row 1, cell 2/td>
        /tr>
        tr>
        td>row 2, cell 1/td>
        td>row 2, cell 2/td>
        /tr>
        /table>
        ` 
    io.WriteString(w, str)
}
 
func main() {
    http.HandleFunc("/hello", handlerHello)     // 注冊   
    err := http.ListenAndServe("localhost:8080", nil)
    if err != nil {
        log.Println(err)
    }
}

再次重啟服務并發(fā)請求, 瀏覽器上顯示的內(nèi)容是:

table border="1">
 tr>
	 td>row 1, cell 1/td>
	 td>row 1, cell 2/td>
 /tr>
 tr>
	 td>row 2, cell 1/td>
	 td>row 2, cell 2/td>
 /tr>
/table>

抓包看一下, 發(fā)現(xiàn)有:Content-Type: text/plain; charset=utf-8

因此, 瀏覽器需要根據(jù)純文本顯示。 注意到, 上述的table左邊少了一個"". 我們加上后,

s.go的代碼如下:

package main 
import (
    "io"
    "log"
    "net/http"
)
 
func handlerHello(w http.ResponseWriter, r *http.Request) {
    str := `
        table border="1">
        tr>
        td>row 1, cell 1/td>
        td>row 1, cell 2/td>
        /tr>
        tr>
        td>row 2, cell 1/td>
        td>row 2, cell 2/td>
        /tr>
        /table>
        ` 
    io.WriteString(w, str)
}
 
func main() {
    http.HandleFunc("/hello", handlerHello)     // 注冊   
    err := http.ListenAndServe("localhost:8080", nil)
    if err != nil {
        log.Println(err)
    }
}

再次重啟服務,發(fā)請求,瀏覽器端的顯示是:

row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

抓包看, 有Content-Type: text/html; charset=utf-8

可見, 服務端會判斷str的格式,來確定Content-Type的類型, 從而決定了瀏覽器端的展示方式。服務端的自動判斷行為, 有點意思。 在我看來, 這樣不太好,應該讓程序員來指定Content-Type.

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • golang中json小談之字符串轉浮點數(shù)的操作
  • go浮點數(shù)轉字符串保留小數(shù)點后N位的完美解決方法
  • 解決Golang中goroutine執(zhí)行速度的問題
  • 解決golang結構體tag編譯錯誤的問題
  • golang 實現(xiàn)Location跳轉方式
  • 對Golang中的FORM相關字段理解
  • golang 打印error的堆棧信息操作
  • golang 比較浮點數(shù)的大小方式

標簽:銅川 梅河口 重慶 雞西 蘭州 吐魯番 汕頭 欽州

巨人網(wǎng)絡通訊聲明:本文標題《解決golang post文件時Content-Type出現(xiàn)的問題》,本文關鍵詞  解決,golang,post,文件,時,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《解決golang post文件時Content-Type出現(xiàn)的問題》相關的同類信息!
  • 本頁收集關于解決golang post文件時Content-Type出現(xiàn)的問題的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    板桥市| 临夏县| 凤阳县| 凌云县| 莲花县| 板桥市| 平江县| 沈阳市| 汽车| 曲松县| 慈溪市| 东乡族自治县| 安岳县| 九江县| 安宁市| 临潭县| 弥渡县| 井陉县| 海阳市| 黑河市| 江城| 蓝田县| 开平市| 云霄县| 巴彦县| 南昌县| 安新县| 滦平县| 兴安县| 兴隆县| 京山县| 霍州市| 自贡市| 奉贤区| 德安县| 彰化市| 灯塔市| 田林县| 金昌市| 黎城县| 额济纳旗|