POST data using the Content-Type multipart/form-data

后端 未结 7 1511
小鲜肉
小鲜肉 2020-11-27 12:16

I\'m trying to upload images from my computer to a website using go. Usually, I use a bash script that sends a file and a key to the server:

curl -F \"image         


        
7条回答
  •  感动是毒
    2020-11-27 13:04

    After having to decode the accepted answer for this question for use in my unit testing I finally ended up with the follow refactored code:

    func createMultipartFormData(t *testing.T, fieldName, fileName string) (bytes.Buffer, *multipart.Writer) {
        var b bytes.Buffer
        var err error
        w := multipart.NewWriter(&b)
        var fw io.Writer
        file := mustOpen(fileName)
        if fw, err = w.CreateFormFile(fieldName, file.Name()); err != nil {
            t.Errorf("Error creating writer: %v", err)
        }
        if _, err = io.Copy(fw, file); err != nil {
            t.Errorf("Error with io.Copy: %v", err)
        }
        w.Close()
        return b, w
    }
    
    func mustOpen(f string) *os.File {
        r, err := os.Open(f)
        if err != nil {
            pwd, _ := os.Getwd()
            fmt.Println("PWD: ", pwd)
            panic(err)
        }
        return r
    }
    
    

    Now it should be pretty easy to use:

        b, w := createMultipartFormData(t, "image","../luke.png")
    
        req, err := http.NewRequest("POST", 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())
    

提交回复
热议问题