Last active
January 31, 2016 13:32
-
-
Save techjanitor/4d02c63fc5159928996c to your computer and use it in GitHub Desktop.
Upload to a multipart/form-data form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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