回答

收藏

使用 Content-Type multipart/form-data POST 数据

技术问答 技术问答 439 人阅读 | 0 人回复 | 2023-09-11

我试着用 go 将图像从我的电脑上传到网站。通常,我用 bash 脚本向服务器发送文件和密钥:  l- }9 i% v" E& x
    curl -F "image"=@"IMAGEFILE" -F "key"="KEY" URL
    ' K3 J8 Q* I1 @2 _9 K% Z) j5 p- j
它工作正常,但我试图把这个请求转换成我的 golang 程序。
# K% V8 X" q: p! p4 J1 R' C* Chttp://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/+ V' ^2 M: D0 ^# _2 N4 _4 ?7 `% ]9 {5 b
我尝试了这个链接和许多其他链接,但服务器对我尝试的每个代码的响应是没有图像,我不知道为什么。如果有人知道上面的例子发生了什么。7 n8 ~, V& O% o+ H' u
                                                                " R3 h: o2 q2 r
    解决方案:                                                               
' o  o& o5 V3 s# t4 B) G. d0 R                                                                这是一些示例代码。
0 ?' k- k& `8 X+ S- X+ z# {简而言之,你需要使用它mime/multipart包来构建表单。) c4 }, E% K2 t3 l
    package mainimport  "bytes"    "fmt"    "io"    "mime/multipart"    "net/http"    "net/http/httptest"    "net/http/httputil"    "os"    "strings")func main()      var client *http.Client    var remoteURL string       setup a mocked http client.        ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request)                b,err := httputil.DumpRequest(r,true)            if err != nil                    panic(err)                                     fmt.Printf("%s",b)    )defer ts.Close()        client = ts.Client()        remoteURL = ts.URL    }    //prepare the reader instances to encode    values := map[string]io.Reader{          "file":  mustOpen("main.go"),// lets assume its this file        "other": strings.NewReader("hello world!"),        err := Upload(client,remoteURL,values)    if err != nil              panic(err)   func Upload(client *http.Client,url string,values map[string]io.Reader) (err error)      / Prepare a form that you will submit to that URL.    var b bytes.Buffer    w := multipart.NewWriter(&b)    for key,r := range values              var fw io.Writer        if x,ok := r.(io.Closer); ok                defer x.Close()          Add an image file        if x,ok := r.(*os.File); ok                if fw,err = w.CreateFormFile(key,x.Name()); err != nil                    return               else                // Add other fields            if fw,err = w.CreateFormField(key); err != nil                    return                      if _,err = io.Copy(fw,r); err != nil                return err        Don't forget to close the multipart writer.    // If you don't close it,your request will be missing the terminating boundary.    w.Close()    // Now that you have a form,you can submit it to your handler.    req,err := http.NewRequest(&quotOST",url,&b)    if err != nil              return    }    // Don't forget to set the content type,this will contain the boundary.    req.Header.Set("Content-Type",w.FormDataContentType()Submit the request    res,err := client.Do(req)    if err != nil              return     Check the response    if res.StatusCode != http.StatusOK              err = fmt.Errorf("bad status: %s",res.Status)   }    return}func mustOpen(f string) *os.File    r,err := os.Open(f)    if err != nil              panic(err)   }    return r}# \, o% W- y. l4 e( j* n
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则