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
+5.7k Fix yum-complete-transaction error
+32.5k Golang : Math pow(the power of x^y) example
+9.5k Golang : Get all countries currencies code in JSON format
+8k Javascript : Put image into Chrome browser's console
+19.9k Golang : Count JSON objects and convert to slice/array
+7.2k Golang : Array mapping with Interface
+21.8k SSL : How to check if current certificate is sha1 or sha2
+19.6k Golang : Close channel after ticker stopped example
+48.6k Golang : Upload file from web browser to server
+10.6k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+9.1k Golang : Capture text return from exec function example