Search code examples
iosswiftalamofiremultipartform-datacodable

How to upload image file using Codable and URLSession.shared.uploadTask (multipart/form-data) in Swift?


I want to upload an image file to the backend server, using certain URL endpoint. I can easily do that using Alamofire's upload request as multipartFormData. However I want to get rid of Alamofire to minimize the dependency on third party frameworks. Here is the Alamofire code, which works:

func uploadRequestAlamofire(parameters: [String: Any], imageData: Data?, completion: @escaping(CustomError?) -> Void ) {

let url = imageUploadEndpoint!

let headers: HTTPHeaders = ["X-User-Agent": "ios",
                            "Accept-Language": "en",
                            "Accept": "application/json",
                            "Content-type": "multipart/form-data",
                            "ApiKey": KeychainService.getString(by: KeychainKey.apiKey) ?? ""]

Alamofire.upload(multipartFormData: { (multipartFormData) in
    for (key, value) in parameters {
        multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
    }

    if let data = imageData {
        multipartFormData.append(data, withName: "file", fileName: "image.png", mimeType: "image/jpg")
    }

}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
    switch result {
    case .success(let upload, _, _):
        upload.responseJSON { response in

            completion(CustomError(errorCode: response.response!.statusCode))

            print("Succesfully uploaded")
        }
    case .failure(let error):
        print("Error in upload: \(error.localizedDescription)")

    }
}
}

Here is the URLSession upload task, which doesn't work:

func requestNativeImageUpload(imageData: Data, orderExtId: String) {

var request = URLRequest(url: imageUploadEndpoint!)
request.httpMethod = "POST"
request.timeoutInterval = 10

    request.allHTTPHeaderFields = [
        "X-User-Agent": "ios",
        "Accept-Language": "en",
        "Accept": "application/json",
        "Content-type": "multipart/form-data",
        "ApiKey": KeychainService.getString(by: KeychainKey.apiKey) ?? ""
    ]

let body = OrderUpload(order_ext_id: orderExtId, file: imageData)

do {
    request.httpBody = try encoder.encode(body)
} catch let error {
    print(error.localizedDescription)
}

let session = URLSession.shared



session.uploadTask(with: request, from: imageData)  { data, response, error in
    guard let response = response as? HTTPURLResponse else { return }

    print(response)
    if error != nil {
        print(error!.localizedDescription)
    }


    }.resume()
}

This is the way I call the methods for both Alamofire and URLSession:

uploadRequestAlamofire(parameters: ["order_ext_id": order_ext_id, "file": "image.jpg"], imageData: uploadImage) { [weak self] response in } 

requestNativeImageUpload(imageData: uploadImage!, orderExtId: order_ext_id)

Here is what the backend server expects to receive in the request body:

let order_ext_id: String
let description: String
let file: string($binary)

This is the Codable struct to encode for request's httpBody.

struct OrderUpload: Codable {
    let order_ext_id: String
    let description: String 
    let file: String
}

Although in this demo my methods may not be fully appropriate and I don't handle the response status code, the Alamofire method works well.

Why shouldn't URLSession work ?


Solution

  • Finally I was able to find the solution. The source is: URLSession: Multipart Form-Data Requests | Swift 3, Xcode 8. In my specific case I need to provide orderExtId as a parameter for the backend server to accept my image. Your case may vary, depending on the requirements of the backend.

    func requestNativeImageUpload(image: UIImage, orderExtId: String) {
    
        guard let url = imageUploadEndpoint else { return }
        let boundary = generateBoundary()
        var request = URLRequest(url: url)
    
        let parameters = ["order_ext_id": orderExtId]
    
        guard let mediaImage = Media(withImage: image, forKey: "file") else { return }
    
        request.httpMethod = "POST"
    
        request.allHTTPHeaderFields = [
                    "X-User-Agent": "ios",
                    "Accept-Language": "en",
                    "Accept": "application/json",
                    "Content-Type": "multipart/form-data; boundary=\(boundary)",
                    "ApiKey": KeychainService.getString(by: KeychainKey.apiKey) ?? ""
                ]
    
        let dataBody = createDataBody(withParameters: parameters, media: [mediaImage], boundary: boundary)
        request.httpBody = dataBody
    
        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }
    
            if let data = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    print(json)
                } catch {
                    print(error)
                }
            }
            }.resume()
    }
    
    
    func generateBoundary() -> String {
        return "Boundary-\(NSUUID().uuidString)"
    }
    
    func createDataBody(withParameters params: [String: String]?, media: [Media]?, boundary: String) -> Data {
    
        let lineBreak = "\r\n"
        var body = Data()
    
        if let parameters = params {
            for (key, value) in parameters {
                body.append("--\(boundary + lineBreak)")
                body.append("Content-Disposition: form-data; name=\"\(key)\"\(lineBreak + lineBreak)")
                body.append("\(value + lineBreak)")
            }
        }
    
        if let media = media {
            for photo in media {
                body.append("--\(boundary + lineBreak)")
                body.append("Content-Disposition: form-data; name=\"\(photo.key)\"; filename=\"\(photo.fileName)\"\(lineBreak)")
                body.append("Content-Type: \(photo.mimeType + lineBreak + lineBreak)")
                body.append(photo.data)
                body.append(lineBreak)
            }
        }
    
        body.append("--\(boundary)--\(lineBreak)")
    
        return body
    }
    
    
    extension Data {
        mutating func append(_ string: String) {
            if let data = string.data(using: .utf8) {
                append(data)
            }
        }
    }
    
    
    struct Media {
        let key: String
        let fileName: String
        let data: Data
        let mimeType: String
    
        init?(withImage image: UIImage, forKey key: String) {
            self.key = key
            self.mimeType = "image/jpg"
            self.fileName = "\(arc4random()).jpeg"
    
            guard let data = image.jpegData(compressionQuality: 0.5) else { return nil }
            self.data = data
        }
    }