Alamofire 4 – Multipart file upload with Swift 3

MultiPart File Upload Swift

Previously I have introduced you to Alamofire and how you can use it to simple HTTP requests and intercept JSON responses. Today, we will speak for a more complex and a must-know topic – how to create a Multipart File Upload request.

Multipart File Upload request

HTTP multipart file upload request is a request that HTTP clients construct to send files and data over to HTTP Server. It is commonly used by HTTP clients to upload files to the server.

In this tutorial, I am showing you how to construct a multipart file upload request, previously tested by me in many other projects so I can guarantee that it is working. This is a copy-paste solution but I would like to explain a bit what is going on. Before we start, don’t forget to install Alamofire and call import Alamofire in your file.

Recommended for you: How to access iOS Camera and Photo Library in Swift 3

func requestWith(endUrl: String, imageData: Data?, parameters: [String : Any], onCompletion: ((JSON?) -> Void)? = nil, onError: ((Error?) -> Void)? = nil){
    
    let url = "http://google.com" /* your API url */
    
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]
    
    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: "image", fileName: "image.png", mimeType: "image/png")
        }
        
    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded")
                if let err = response.error{
                    onError?(err)
                    return
                }
                onCompletion?(nil)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            onError?(error)
        }
    }
}

Arguments

I have created this function to support as many arguments as possible. I will start by order:

  • endUrl: String – I suppose you are keeping your base URL in some other helper function (for this presentation I have hard coded it in the url variable), so this argument will be for attaching the endpoint to your base URL.
  • imageData: Data? – this is an argument that you need to pass your UIImage converted in a Data type. It is optional, so you can pass nil if you don’t have an image to pass.
  •  parameters: [String : Any] – an argument where you need to pass your additional key value POST parameters. Pass an empty key – value object, if you don’t have any.
  • onCompletition – a closure block where you will pass the success response
  • onError – a closure block where you will pass the error response

If you don’t know how to convert UIImage to Data, here is a snippet that can help you:

let img = UIImage(named:"someImage.png")
let data = UIImageJPEGRepresentation(img, 1.0)

 


I really hope that this tutorial helped you discover how to create multipart file upload requests. If you have any questions please leave a comment in the comments section. Also, spread the word by sharing this post and subscribe to my newsletter for more awesome Swift tutorials and news. Cheers! 🙂

Recommended for you: How to convert HTML using NSAttributedString
Follow me on Medium, for more interesting Swift programming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *