This chapter introduces the methods for file upload and download using the Go Resty library.
Multipart File Upload
Upload files via Multipart POST request
// Read two files first
profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt")
// Create a Resty client
client := resty.New()
// Use SetFileReader to set the file and parameters automatically for upload
// Use SetFormData to set other form parameters
resp, err := client.R().
SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
SetFormData(map[string]string{
"first_name": "Jeevanandam",
"last_name": "M",
}).
Post("http://www.tizi365.com/upload")
Directly Upload Local Files
This is more convenient than the above, as it can directly upload local files without the need to read the file first.
// Create a Resty client
client := resty.New()
// Use SetFile to set the file to upload and the bound request parameter field
resp, err := client.R().
SetFile("profile_img", "/Users/jeeva/test-img.png").
Post("http://myapp.com/upload")
// Batch upload files using SetFiles
resp, err := client.R().
SetFiles(map[string]string{
"profile_img": "/Users/jeeva/test-img.png",
"notes": "/Users/jeeva/text-file.txt",
}).
Post("http://myapp.com/upload")
// Batch upload files and set other form parameters at the same time
resp, err := client.R().
SetFiles(map[string]string{
"profile_img": "/Users/jeeva/test-img.png",
"notes": "/Users/jeeva/text-file.txt",
}).
SetFormData(map[string]string{
"first_name": "Jeevanandam",
"last_name": "M",
"zip_code": "00001",
"city": "my city",
"access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
}).
Post("http://myapp.com/profile")
Download Files
// Create a Resty client
client := resty.New()
// Set the file output directory, Resty will automatically create it if it doesn't exist
// This setting is optional if SetOutput parameter is set with an absolute path.
client.SetOutputDirectory("/Users/tizi365/Downloads")
// Send an HTTP request here and save the request result to the file path set by SetOutput parameter
_, err := client.R().
SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip").
Get("http://bit.ly/1LouEKr")
// Here is an example using an absolute path
_, err := client.R().
SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip").
Get("http://bit.ly/1LouEKr")