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
+11k Golang : 2 dimensional array example
+4.5k Javascript : Shuffle or randomize array example
+3.9k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+11.9k Golang : List objects in AWS S3 bucket
+6.8k Golang : Sort words with first uppercase letter
+18.4k Swift : Convert (cast) Int to int32 or Uint32
+9.1k Golang : cannot assign type int to value (type uint8) in range error
+26k Golang : Record voice(audio) from microphone to .WAV file
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+5.2k Golang : Join lines with certain suffix symbol example
+40.2k Golang : Convert string to array/slice
+5.2k Linux/Unix : Commands that you need to be careful about