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
+21.7k Golang : How to reverse slice or array elements order
+5.4k Golang : Stop goroutine without channel
+17.9k Golang : Get all upper case or lower case characters from string example
+10.2k Golang : Random Rune generator
+14.1k Golang : Chunk split or divide a string into smaller chunk example
+17.8k Golang : Qt image viewer example
+24k Golang : Upload to S3 with official aws-sdk-go package
+12.1k Golang : Split strings into command line arguments
+6k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+15.3k Golang : Get all local users and print out their home directory, description and group id
+11.5k Golang : Display a text file line by line with line number example