How to upload a picture url's content by form POST without local storage in Golang

Server environment

1
2
3
4
5
$ cat /etc/issue
Ubuntu 16.04 LTS

# go version
go version go1.8.4 linux/amd64

Recently, i want to download a few pictures as my souvenirs, but these pictures all comes from other people’s website link.
And i have a personal image server which have form post api.
So this program will finished these steps in this tutorial with a few line code.

  • Download a picture and save in memory temporary as byte buffer
  • Generate a post form and include picture ‘s information and content
  • Http request to image server

The key is to set a new multipart.Writer

Download a picture

It ‘s so sample to do this.

1
resp, err := req.Get(imageUrl)

Init a empty byte buffer

1
body = &bytes.Buffer{}

Init a writer

1
writer := multipart.NewWriter(body)

The mime/multipart package hides all the complexity of creating a multipart request.

Create a writer form and init a fired for picture

1
writerField, err := writer.CreateFormField("file")

Create a part for the file form entry with the name of the file param and the name of the file.

Translate the picture as byte buffer

1
2
3
4
5
6
_, err = io.Copy(writerField, resp.Response().Body)
if err != nil {
return body, "", err
}

writer.Close()

We need to add the content of the file to the file part, we use the io.Copy() to do so.
The multipart.Writer takes care of setting the boundary and formatting the form data for us, nice isn’t it?!

  • Don’t forget to close our writer.

One last thing before post form request, you should know the form content type

1
contentType := writer.FormDataContentType()

New a Post form request

1
2
request, err := http.NewRequest("POST", apiUrl, body)
request.Header.Set("Content-Type", contentType)

Send this request

1
2
3

client := &http.Client{}
response, err := client.Do(request)

This tutorial is written based on Static file upload.
Hopefully this example will be helpful to some of you.

Share