Multipart 파일 업로드

Go Resty 라이브러리를 사용하여 Multipart POST 요청을 통해 파일을 업로드합니다.

// 먼저 두 개의 파일을 읽습니다
profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt")

// Resty 클라이언트 생성
client := resty.New()

// SetFileReader를 사용하여 파일 및 매개변수를 자동으로 설정하여 업로드합니다
// 다른 양식 매개변수를 설정하려면 SetFormData를 사용합니다
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")

로컬 파일 직접 업로드

이 방법은 파일을 먼저 읽지 않고 로컬 파일을 직접 업로드할 수 있어 더 편리합니다.

// Resty 클라이언트 생성
client := resty.New()

// SetFile를 사용하여 파일을 업로드하고 바운드 요청 매개변수 필드를 설정합니다
resp, err := client.R().
      SetFile("profile_img", "/Users/jeeva/test-img.png").
      Post("http://myapp.com/upload")

// 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")

// 일괄 파일 업로드 및 동시에 다른 양식 매개변수 설정
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": "내 도시",
        "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
      }).
      Post("http://myapp.com/profile")

파일 다운로드

// Resty 클라이언트 생성
client := resty.New()

// 파일 출력 디렉토리 설정, 해당 경로가 없다면 Resty가 자동으로 생성합니다
// SetOutput 매개변수에 절대 경로가 설정되어 있으면 이 설정은 선택 사항입니다.
client.SetOutputDirectory("/Users/tizi365/Downloads")

// 여기서 HTTP 요청을 보내고 SetOutput 매개변수에 설정된 파일 경로에 요청 결과를 저장합니다
_, err := client.R().
          SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")

// 절대 경로를 사용하는 예시
_, err := client.R().
          SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")