0

I need to send some text data alongside with the image(multipart) via Alamofire, for example:

{
    "name": "Me",
    "age":  "23",
    "image": file_goes_here
}

I know how to send text data and image as multipart separately, but I do not know how can I send all it in one, the same, request. Is it possible?

John Doe
  • 811
  • 4
  • 14
  • 26

2 Answers2

0

You can use something like this -

Alamofire.upload(.POST, urlString, headers: nil, multipartFormData: { (multipartFormData) -> Void in

    multipartFormData.appendBodyPart(data: name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"name")
    multipartFormData.appendBodyPart(data: age.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"age")
    //.....

    }, encodingCompletion: { encodingResult in
        //...

        }
    }
)
Rahul Mane
  • 1,005
  • 18
  • 33
Marina
  • 1,177
  • 4
  • 14
  • 27
0

You can encode image data to base64 format.

// Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageName")!
let imageData = UIImagePNGRepresentation(image)

Swift 2.0 Encoding

let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

Swift 2.0 Decoding

let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) 

Then attach the base64 string into post data

{
    "name": "Me",
    "age":  "23",
    "image": base64String
}
BobGao
  • 770
  • 8
  • 18