conchimnon conchimnon -4 years ago 167
HTTP Question

How to upload image file in the request body with Alamofire?

I'm new to iOS development, and right now I'm writing an app using Alamofire to upload image to server, but after hours of looking for solutions and reading documentation, I still have not made it work yet. Can someone please help? Thanks. This is my code so far:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imagePicker.dismiss(animated: true, completion: nil)

//Upload image from here
//Get user for header info
var user = User.getUserInstance()

//Get current patient for header info
var currentPatient = CurrentPatient.getCurrentPatientInstance()

//Server address
let serverAddress = user.serverAddress

//Prep for headers
var headers = [
"ISHC_LOGIN": user.username,
"ISHC_PWD": user.password,
"Accept-Encoding": "application/xml"


let request = Alamofire.upload(multipartFormData: { multipartFormData in
let imageData = UIImagePNGRepresentation(image)
multipartFormData.append(imageData!, withName: "image", fileName: "file.png", mimeType: "image/png")
// multipartFormData.append(( .utf8))!, withName: key)

}, to: serverAddress, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
debugPrint("RESPONSE IS:\(response)")
case .failure(let encodingError):
debugPrint("request is:\(request)")

Based on the API (I'm only the front-end dev), I can upload the image using the request body and can keep the image file as is (no encoding required), but I'm not sure using
is a correct solution. Also, when I try to print out the request, I did not see the whole curl command.

Answer Source

Try to save the selected image from UIImagePickerController in Directory

    func saveUserProfileAtDirectory (userImage : UIImage) -> NSURL {

    let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    // create a name for your image
    let imageURL = documentsDirectoryURL.URLByAppendingPathComponent("pic.jpg")

    if NSFileManager.defaultManager().fileExistsAtPath(imageURL.path!) {

        do {
            try NSFileManager.defaultManager().removeItemAtPath(imageURL.path!)


    if UIImageJPEGRepresentation(userImage, 1.0)!.writeToFile(imageURL.path!, atomically: true) {

        return imageURL

    } else {
        print("error saving file")

    return NSURL()


Then use imageURL in almofire:

multipartFormData.appendBodyPart(fileURL: imageURL, name: "ISHC_IMAGE_NAME")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download