Skip to content

Instantly share code, notes, and snippets.

@techjanitor
Last active January 31, 2016 13:32
Show Gist options
  • Save techjanitor/4d02c63fc5159928996c to your computer and use it in GitHub Desktop.
Save techjanitor/4d02c63fc5159928996c to your computer and use it in GitHub Desktop.
Upload to a multipart/form-data form
func UploadPosts(file, date, name, comment, url string) (err error) {
// Make a new multipart writer with a buffer
var b bytes.Buffer
w := multipart.NewWriter(&b)
// This is just a random form field
if err = w.WriteField("name", name); err != nil {
return
}
if err = w.WriteField("comment", comment); err != nil {
return
}
if err = w.WriteField("date", date); err != nil {
return
}
// This just takes a string of the file name
if file != "" {
filename := img_dir + file
f, err := os.Open(filename)
if err != nil {
return err
}
// CreateFormFile adds the file to the multipart writer
fw, err := w.CreateFormFile("file", filename)
if err != nil {
return err
}
if _, err = io.Copy(fw, f); err != nil {
return err
}
}
// Close the multipart writer
w.Close()
// Make a post request with our writer
req, err := http.NewRequest("POST", url, &b)
if err != nil {
return
}
// Adds content-type header
req.Header.Add("Content-Type", w.FormDataContentType())
// create http client and execute request with Do()
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
// DumpResponse just to check for error messages
body, err := httputil.DumpResponse(res, true)
if err != nil {
return
}
// Print anything to stdout
fmt.Println(string(body))
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment