ios,swift2023. 5. 22. 12:49

[iOS] URLSession multipart/form-data swagger 이미지 보내기

 

s3 라이브러리로 이미지를 보냈었는데, region 설정이 제대로 안되는 이슈가 발생했다..

 

예를 들어 northeast-2 로 configuration 설정을 햇는데, southeast-2 로 간다던지? 

 

그래서 방향을 바꿔 클라이언트 -> 서버 -> s3로 보내기로 했다..

 

URLSesstion 이용해서 swegger 설정한데로 보내려면 어떻게 해야 할까??

 

key -> file 이라고 설정했고

 

// 이미지 data
let data : Data = self.image.jpegData(compressionQuality: 1.0)!
        
        let url : String = "~~~~~"
        
        let urlObj = URL(string: url)
        var request = URLRequest(url: urlObj!)
        
        // header -> Content-Type , UUID -> boundaray key 
        let boundary = "Boundary_\(UUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        var httpBody = Data()
        
        // 이미지 파일 이름 
        let name = "name"
        
        let filePathKey = "file"
        
        // 중요 -> 시작과 끝 설정
        let boundaryPrefix = "--\(boundary)\r\n"
        let boundaryPrefixEnd = "--\(boundary)--\r\n"
        
        // 시작
        httpBody.append(boundaryPrefix.data(using: .utf8)!)
        
        // filePathKey -> swagger key , name -> file name
        httpBody.append("Content-Disposition: form-data;  name=\"\(filePathKey)\"; filename=\"\(name)\"\r\n".data(using: .utf8)!)
        httpBody.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
        
        // image data
        httpBody.append(data)
        httpBody.append("\r\n".data(using: .utf8)!)
       
       	// 끝
        httpBody.append(boundaryPrefixEnd.data(using: .utf8)!)
                        
        request.httpBody = httpBody
        request.httpMethod = "POST"
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let response = response as? HTTPURLResponse ,response.statusCode >= 200,response.statusCode <= 299 else
            {
                print("-> testS3APi -> end -> fail")
                return
            }
            
            print("-> testS3APi -> end -> success")
        }
        
        task.resume()
Posted by thdeodls85