Sidebar

x

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

 Server environment

$ 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.

resp, err := req.Get(imageUrl)
 

Init a empty byte buffer

body = &bytes.Buffer{}
 

Init a writer

Enter your text here ...

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

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

_, 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

contentType := writer.FormDataContentType()
 

New a Post form request

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

Send this request

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.

Implement a web shell interface using Flask
How to install Squid 4.2 on CentOS
 

Comments 1

Muhammad Husnain on Friday, 14 December 2018 15:23

nice

Already Registered? Login Here
Guest
Sunday, 16 December 2018