ashwin shrestha ashwin shrestha - 5 months ago 56
Swift Question

Multipart-form (image,parameters,headers) Post request with Alamofire in swift

Firstly, i want to say i am new to swift, and know a little.So any help would be appriciated. I have a multipart-data form which has a image (profile-image), a few parameters (first-name, last-name) and headers(userid, hashCode). I want to send a POST request to submit the form.

I have been able to make POST request with only, headers and other parameters except image as:

let headers = [
"user_id": (Helper.getUserInfo()?.user_id)!,
let params = [

Alamofire.request(.POST, kFormUrl, parameters:params ,headers:headers).responseJSON { [weak self] response in

//working fine

But how to send image as a file (not base-64string) i.e. direct file upload with parameters and headers.

Thanks in advance


you can use Alamofire 3.0+ below code

func uploadImageAndData(){
 let gender    = "M"
let firstName = "firstName"
let lastName  = "lastName"
let dob       = "11-Jan-2000"
let aboutme   = "aboutme"
let token     = "token"

var parameters = [String:AnyObject]()
parameters = ["gender":gender,"firstName":firstName,"dob":dob,"aboutme":aboutme,"token":token,"lastName":lastName]

let URL = "http://yourserviceurl/"
let image = UIImage(named: "image.png")

Alamofire.upload(.POST, URL, multipartFormData: {
  multipartFormData in
if  let imageData = UIImageJPEGRepresentation(image, 0.6) {
 multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
for (key, value) in parameters {
 multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}, encodingCompletion: {
 encodingResult in

 switch encodingResult {
  case .Success(let upload, _, _):
    upload.responseJSON { response in
        print(response.request)  // original URL request
        print(response.response) // URL response
        print(     // server data
        print(response.result)   // result of response serialization

        if let JSON = response.result.value {
            print("JSON: \(JSON)")

  case .Failure(let encodingError):