Golang mime/multipart.CreateFormFile(), CreateFormField() and FormDataContentType() functions example
package mime/multipart
Golang mime/multipart.CreateFormFile(), CreateFormField() and FormDataContentType() functions usage example
var url string
var file string
// Prepare a form that you will submit to that URL.
var buff bytes.Buffer
w := multipart.NewWriter(&buff)
// Add your image file
f, err := os.Open(file)
if err != nil {
return
}
fw, err := w.CreateFormFile("image", file)
if err != nil {
return
}
if _, err = io.Copy(fw, f); err != nil {
return
}
// Add the other fields
if fw, err = w.CreateFormField("key"); err != nil {
return
}
if _, err = fw.Write([]byte("KEY")); err != nil {
return
}
// 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("POST", url, &buff)
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
client := &http.Client{}
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
References :
http://golang.org/pkg/mime/multipart/#Writer.CreateFormField
http://golang.org/pkg/mime/multipart/#Writer.FormDataContentType
Advertisement
Something interesting
Tutorials
+4.8k Chrome : How to block socketloop.com links in Google SERP?
+32.3k Golang : Convert []string to []byte examples
+14.6k Golang : How to pass map to html template and access the map's elements
+9.2k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+43.8k Golang : Get hardware information such as disk, memory and CPU usage
+11.2k Golang : Read until certain character to break for loop
+16k Golang : Update database with GORM example
+21.6k Curl usage examples with Golang
+7.6k Golang : Process json data with Jason package
+5.2k Swift : Convert (cast) Float to Int or Int32 value
+6.6k Golang : Spell checking with ispell example
+9.9k Golang : Qt get screen resolution and display on center example