What's the problem
I have a url with an image in it, and I want to send the image in a post request. Is there a way to do it without downloading the file locally?
What have I tried
Usually I would download the image, send the image, and delete the file. Is there a better way?
response, e := http.Get(url)
if e != nil {
log.Fatal(e)
}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
You don't need to create a temporary file. Remember that http.Request
takes an io.Reader
(or an io.ReadCloser
), and since response.Body
is an io.ReadCloser
it will happily read directly from your existing HTTP response body from your previous request.
req, err := http.NewRequest("POST", url, response.Body)
For a multipart upload, you can simply call multipart.CreatePart()
and then io.Copy()
directly from the response body of the original HTTP GET request to the writer you're using. You still don't need a temporary file.