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












8















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)!,
"hash_code":(Helper.getUserInfo()?.hash_code)!,
]
let params = [
"name": self.name.text!,
"address":self.address.text!]


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










share|improve this question



























    8















    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)!,
    "hash_code":(Helper.getUserInfo()?.hash_code)!,
    ]
    let params = [
    "name": self.name.text!,
    "address":self.address.text!]


    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










    share|improve this question

























      8












      8








      8


      3






      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)!,
      "hash_code":(Helper.getUserInfo()?.hash_code)!,
      ]
      let params = [
      "name": self.name.text!,
      "address":self.address.text!]


      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










      share|improve this question














      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)!,
      "hash_code":(Helper.getUserInfo()?.hash_code)!,
      ]
      let params = [
      "name": self.name.text!,
      "address":self.address.text!]


      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







      ios swift alamofire






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 20 '16 at 3:14









      ashwin shresthaashwin shrestha

      58117




      58117
























          4 Answers
          4






          active

          oldest

          votes


















          9














          you can use Alamofire 3.0+ below code



          func uploadImageAndData(){
          //parameters
          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, _, _):
          print("s")
          upload.responseJSON { response in
          print(response.request) // original URL request
          print(response.response) // URL response
          print(response.data) // server data
          print(response.result) // result of response serialization

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

          case .Failure(let encodingError):
          print(encodingError)
          }
          })
          }





          share|improve this answer



















          • 5





            Alamofire 4.0 Example?

            – Peter Kreinz
            Oct 20 '16 at 11:14






          • 1





            How to add headers in multiform data in Almofire 3.0?

            – Chanchal Warde
            Feb 6 '17 at 13:27











          • go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

            – amit gupta
            Feb 7 '17 at 4:15











          • @Amit Gupta, can you give me an example for Alamofire 4.0?

            – Gautam Sareriya
            Apr 11 '17 at 7:43





















          1














             let userImageURL = NSURL(string: "your image url" as String)
          let data = NSData.init(contentsOfURL: userImageURL!)


          Alamofire.upload(
          .POST,registerUrl!,
          multipartFormData: { multipartFormData in

          multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")

          multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")

          multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")

          multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")


          },
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .Success(let upload, _, _):
          upload.responseJSON { response in
          print(response)
          let dict = response.result.value as! NSDictionary

          }
          case .Failure(let encodingError):
          print(encodingError)
          }
          }
          )





          share|improve this answer































            1














            I use Alamofire (Swift 2.3) to send multipart with progress.



            func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
            let headers:[String: String] = [:]

            let router = URLRequest.URLRequest
            let tuple = URLRequest.parameters
            let parameters = tuple.0!
            let imagesData = tuple.1
            let url = router.URLString

            self.manager!.upload(
            .POST,
            url,
            headers: headers,
            multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
            for value in imagesData {
            var mimeType = "video/jpg"
            var bodyName = "images"
            let filename = value.uniqueName
            if value.mediaType == ReporterMediaType.image {
            mimeType = "image/jpg"
            bodyName = "images"
            } else if value.mediaType == ReporterMediaType.video {
            mimeType = "video/quicktime"
            bodyName = "video"
            } else if value.mediaType == ReporterMediaType.videoFrame {
            mimeType = "image/jpg"
            bodyName = "videoFrame"
            }
            multipartFormData.appendBodyPart(
            data: value.data,
            name: bodyName,
            fileName: filename,
            mimeType: mimeType)
            }
            for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }
            },
            encodingCompletion: { (encodingResult) -> Void in
            switch encodingResult {
            case .Success(let upload, _, _):
            upload.responseJSON { response in
            if response.result.isSuccess || response.response?.statusCode == 200 {
            completion(json: upload, error: nil)
            } else {
            dispatch_async(dispatch_get_main_queue()) {
            completion(json: nil, error: response.result.error)
            }
            }
            }
            upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
            let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
            onProgress(progress: progress)
            }
            case .Failure:
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            break
            }
            }) }





            share|improve this answer































              1














              func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
              var headers = Alamofire.SessionManager.defaultHTTPHeaders
              headers["Headerkey"] = "Headerkey"

              Alamofire.upload(multipartFormData:
              { (multipartFormData) in

              if data != nil {
              multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
              }else{
              multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
              }

              for (key, value) in jsonInput
              {
              multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
              }
              }, to:url, method: .post, headers: headers)
              { (result) in
              switch result {
              case .success(let upload, _ , _ ):
              upload.uploadProgress(closure:
              { (progress) in
              print(String(format:"%.0f%@",Float(progress.fractionCompleted)*100,"%")))

              })

              upload.responseJSON { response in
              if showLoader == true
              {
              MBProgressHUD.hide(for: controller.view, animated: true)
              }

              completion(response)

              }
              case .failure(let encodingError):
              print(encodingError.localizedDescription)

              break
              }
              }
              }





              share|improve this answer

























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34890922%2fmultipart-form-image-parameters-headers-post-request-with-alamofire-in-swift%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                9














                you can use Alamofire 3.0+ below code



                func uploadImageAndData(){
                //parameters
                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, _, _):
                print("s")
                upload.responseJSON { response in
                print(response.request) // original URL request
                print(response.response) // URL response
                print(response.data) // server data
                print(response.result) // result of response serialization

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

                case .Failure(let encodingError):
                print(encodingError)
                }
                })
                }





                share|improve this answer



















                • 5





                  Alamofire 4.0 Example?

                  – Peter Kreinz
                  Oct 20 '16 at 11:14






                • 1





                  How to add headers in multiform data in Almofire 3.0?

                  – Chanchal Warde
                  Feb 6 '17 at 13:27











                • go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                  – amit gupta
                  Feb 7 '17 at 4:15











                • @Amit Gupta, can you give me an example for Alamofire 4.0?

                  – Gautam Sareriya
                  Apr 11 '17 at 7:43


















                9














                you can use Alamofire 3.0+ below code



                func uploadImageAndData(){
                //parameters
                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, _, _):
                print("s")
                upload.responseJSON { response in
                print(response.request) // original URL request
                print(response.response) // URL response
                print(response.data) // server data
                print(response.result) // result of response serialization

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

                case .Failure(let encodingError):
                print(encodingError)
                }
                })
                }





                share|improve this answer



















                • 5





                  Alamofire 4.0 Example?

                  – Peter Kreinz
                  Oct 20 '16 at 11:14






                • 1





                  How to add headers in multiform data in Almofire 3.0?

                  – Chanchal Warde
                  Feb 6 '17 at 13:27











                • go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                  – amit gupta
                  Feb 7 '17 at 4:15











                • @Amit Gupta, can you give me an example for Alamofire 4.0?

                  – Gautam Sareriya
                  Apr 11 '17 at 7:43
















                9












                9








                9







                you can use Alamofire 3.0+ below code



                func uploadImageAndData(){
                //parameters
                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, _, _):
                print("s")
                upload.responseJSON { response in
                print(response.request) // original URL request
                print(response.response) // URL response
                print(response.data) // server data
                print(response.result) // result of response serialization

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

                case .Failure(let encodingError):
                print(encodingError)
                }
                })
                }





                share|improve this answer













                you can use Alamofire 3.0+ below code



                func uploadImageAndData(){
                //parameters
                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, _, _):
                print("s")
                upload.responseJSON { response in
                print(response.request) // original URL request
                print(response.response) // URL response
                print(response.data) // server data
                print(response.result) // result of response serialization

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

                case .Failure(let encodingError):
                print(encodingError)
                }
                })
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 16 '16 at 17:20









                amit guptaamit gupta

                1,006927




                1,006927








                • 5





                  Alamofire 4.0 Example?

                  – Peter Kreinz
                  Oct 20 '16 at 11:14






                • 1





                  How to add headers in multiform data in Almofire 3.0?

                  – Chanchal Warde
                  Feb 6 '17 at 13:27











                • go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                  – amit gupta
                  Feb 7 '17 at 4:15











                • @Amit Gupta, can you give me an example for Alamofire 4.0?

                  – Gautam Sareriya
                  Apr 11 '17 at 7:43
















                • 5





                  Alamofire 4.0 Example?

                  – Peter Kreinz
                  Oct 20 '16 at 11:14






                • 1





                  How to add headers in multiform data in Almofire 3.0?

                  – Chanchal Warde
                  Feb 6 '17 at 13:27











                • go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                  – amit gupta
                  Feb 7 '17 at 4:15











                • @Amit Gupta, can you give me an example for Alamofire 4.0?

                  – Gautam Sareriya
                  Apr 11 '17 at 7:43










                5




                5





                Alamofire 4.0 Example?

                – Peter Kreinz
                Oct 20 '16 at 11:14





                Alamofire 4.0 Example?

                – Peter Kreinz
                Oct 20 '16 at 11:14




                1




                1





                How to add headers in multiform data in Almofire 3.0?

                – Chanchal Warde
                Feb 6 '17 at 13:27





                How to add headers in multiform data in Almofire 3.0?

                – Chanchal Warde
                Feb 6 '17 at 13:27













                go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                – amit gupta
                Feb 7 '17 at 4:15





                go to this link github.com/Alamofire/Alamofire#http-headers @ChanWarde

                – amit gupta
                Feb 7 '17 at 4:15













                @Amit Gupta, can you give me an example for Alamofire 4.0?

                – Gautam Sareriya
                Apr 11 '17 at 7:43







                @Amit Gupta, can you give me an example for Alamofire 4.0?

                – Gautam Sareriya
                Apr 11 '17 at 7:43















                1














                   let userImageURL = NSURL(string: "your image url" as String)
                let data = NSData.init(contentsOfURL: userImageURL!)


                Alamofire.upload(
                .POST,registerUrl!,
                multipartFormData: { multipartFormData in

                multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")

                multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")

                multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")

                multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")


                },
                encodingCompletion: { encodingResult in
                switch encodingResult {
                case .Success(let upload, _, _):
                upload.responseJSON { response in
                print(response)
                let dict = response.result.value as! NSDictionary

                }
                case .Failure(let encodingError):
                print(encodingError)
                }
                }
                )





                share|improve this answer




























                  1














                     let userImageURL = NSURL(string: "your image url" as String)
                  let data = NSData.init(contentsOfURL: userImageURL!)


                  Alamofire.upload(
                  .POST,registerUrl!,
                  multipartFormData: { multipartFormData in

                  multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")

                  multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")

                  multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")

                  multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")


                  },
                  encodingCompletion: { encodingResult in
                  switch encodingResult {
                  case .Success(let upload, _, _):
                  upload.responseJSON { response in
                  print(response)
                  let dict = response.result.value as! NSDictionary

                  }
                  case .Failure(let encodingError):
                  print(encodingError)
                  }
                  }
                  )





                  share|improve this answer


























                    1












                    1








                    1







                       let userImageURL = NSURL(string: "your image url" as String)
                    let data = NSData.init(contentsOfURL: userImageURL!)


                    Alamofire.upload(
                    .POST,registerUrl!,
                    multipartFormData: { multipartFormData in

                    multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")

                    multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")

                    multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")

                    multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")


                    },
                    encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .Success(let upload, _, _):
                    upload.responseJSON { response in
                    print(response)
                    let dict = response.result.value as! NSDictionary

                    }
                    case .Failure(let encodingError):
                    print(encodingError)
                    }
                    }
                    )





                    share|improve this answer













                       let userImageURL = NSURL(string: "your image url" as String)
                    let data = NSData.init(contentsOfURL: userImageURL!)


                    Alamofire.upload(
                    .POST,registerUrl!,
                    multipartFormData: { multipartFormData in

                    multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")

                    multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")

                    multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")

                    multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")


                    },
                    encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .Success(let upload, _, _):
                    upload.responseJSON { response in
                    print(response)
                    let dict = response.result.value as! NSDictionary

                    }
                    case .Failure(let encodingError):
                    print(encodingError)
                    }
                    }
                    )






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 31 '16 at 14:12









                    Hrishikesh MenonHrishikesh Menon

                    12010




                    12010























                        1














                        I use Alamofire (Swift 2.3) to send multipart with progress.



                        func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
                        let headers:[String: String] = [:]

                        let router = URLRequest.URLRequest
                        let tuple = URLRequest.parameters
                        let parameters = tuple.0!
                        let imagesData = tuple.1
                        let url = router.URLString

                        self.manager!.upload(
                        .POST,
                        url,
                        headers: headers,
                        multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
                        for value in imagesData {
                        var mimeType = "video/jpg"
                        var bodyName = "images"
                        let filename = value.uniqueName
                        if value.mediaType == ReporterMediaType.image {
                        mimeType = "image/jpg"
                        bodyName = "images"
                        } else if value.mediaType == ReporterMediaType.video {
                        mimeType = "video/quicktime"
                        bodyName = "video"
                        } else if value.mediaType == ReporterMediaType.videoFrame {
                        mimeType = "image/jpg"
                        bodyName = "videoFrame"
                        }
                        multipartFormData.appendBodyPart(
                        data: value.data,
                        name: bodyName,
                        fileName: filename,
                        mimeType: mimeType)
                        }
                        for (key, value) in parameters {
                        multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                        }
                        },
                        encodingCompletion: { (encodingResult) -> Void in
                        switch encodingResult {
                        case .Success(let upload, _, _):
                        upload.responseJSON { response in
                        if response.result.isSuccess || response.response?.statusCode == 200 {
                        completion(json: upload, error: nil)
                        } else {
                        dispatch_async(dispatch_get_main_queue()) {
                        completion(json: nil, error: response.result.error)
                        }
                        }
                        }
                        upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                        let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
                        onProgress(progress: progress)
                        }
                        case .Failure:
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                        break
                        }
                        }) }





                        share|improve this answer




























                          1














                          I use Alamofire (Swift 2.3) to send multipart with progress.



                          func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
                          let headers:[String: String] = [:]

                          let router = URLRequest.URLRequest
                          let tuple = URLRequest.parameters
                          let parameters = tuple.0!
                          let imagesData = tuple.1
                          let url = router.URLString

                          self.manager!.upload(
                          .POST,
                          url,
                          headers: headers,
                          multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
                          for value in imagesData {
                          var mimeType = "video/jpg"
                          var bodyName = "images"
                          let filename = value.uniqueName
                          if value.mediaType == ReporterMediaType.image {
                          mimeType = "image/jpg"
                          bodyName = "images"
                          } else if value.mediaType == ReporterMediaType.video {
                          mimeType = "video/quicktime"
                          bodyName = "video"
                          } else if value.mediaType == ReporterMediaType.videoFrame {
                          mimeType = "image/jpg"
                          bodyName = "videoFrame"
                          }
                          multipartFormData.appendBodyPart(
                          data: value.data,
                          name: bodyName,
                          fileName: filename,
                          mimeType: mimeType)
                          }
                          for (key, value) in parameters {
                          multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                          }
                          },
                          encodingCompletion: { (encodingResult) -> Void in
                          switch encodingResult {
                          case .Success(let upload, _, _):
                          upload.responseJSON { response in
                          if response.result.isSuccess || response.response?.statusCode == 200 {
                          completion(json: upload, error: nil)
                          } else {
                          dispatch_async(dispatch_get_main_queue()) {
                          completion(json: nil, error: response.result.error)
                          }
                          }
                          }
                          upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                          let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
                          onProgress(progress: progress)
                          }
                          case .Failure:
                          UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                          break
                          }
                          }) }





                          share|improve this answer


























                            1












                            1








                            1







                            I use Alamofire (Swift 2.3) to send multipart with progress.



                            func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
                            let headers:[String: String] = [:]

                            let router = URLRequest.URLRequest
                            let tuple = URLRequest.parameters
                            let parameters = tuple.0!
                            let imagesData = tuple.1
                            let url = router.URLString

                            self.manager!.upload(
                            .POST,
                            url,
                            headers: headers,
                            multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
                            for value in imagesData {
                            var mimeType = "video/jpg"
                            var bodyName = "images"
                            let filename = value.uniqueName
                            if value.mediaType == ReporterMediaType.image {
                            mimeType = "image/jpg"
                            bodyName = "images"
                            } else if value.mediaType == ReporterMediaType.video {
                            mimeType = "video/quicktime"
                            bodyName = "video"
                            } else if value.mediaType == ReporterMediaType.videoFrame {
                            mimeType = "image/jpg"
                            bodyName = "videoFrame"
                            }
                            multipartFormData.appendBodyPart(
                            data: value.data,
                            name: bodyName,
                            fileName: filename,
                            mimeType: mimeType)
                            }
                            for (key, value) in parameters {
                            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                            }
                            },
                            encodingCompletion: { (encodingResult) -> Void in
                            switch encodingResult {
                            case .Success(let upload, _, _):
                            upload.responseJSON { response in
                            if response.result.isSuccess || response.response?.statusCode == 200 {
                            completion(json: upload, error: nil)
                            } else {
                            dispatch_async(dispatch_get_main_queue()) {
                            completion(json: nil, error: response.result.error)
                            }
                            }
                            }
                            upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                            let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
                            onProgress(progress: progress)
                            }
                            case .Failure:
                            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                            break
                            }
                            }) }





                            share|improve this answer













                            I use Alamofire (Swift 2.3) to send multipart with progress.



                            func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
                            let headers:[String: String] = [:]

                            let router = URLRequest.URLRequest
                            let tuple = URLRequest.parameters
                            let parameters = tuple.0!
                            let imagesData = tuple.1
                            let url = router.URLString

                            self.manager!.upload(
                            .POST,
                            url,
                            headers: headers,
                            multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
                            for value in imagesData {
                            var mimeType = "video/jpg"
                            var bodyName = "images"
                            let filename = value.uniqueName
                            if value.mediaType == ReporterMediaType.image {
                            mimeType = "image/jpg"
                            bodyName = "images"
                            } else if value.mediaType == ReporterMediaType.video {
                            mimeType = "video/quicktime"
                            bodyName = "video"
                            } else if value.mediaType == ReporterMediaType.videoFrame {
                            mimeType = "image/jpg"
                            bodyName = "videoFrame"
                            }
                            multipartFormData.appendBodyPart(
                            data: value.data,
                            name: bodyName,
                            fileName: filename,
                            mimeType: mimeType)
                            }
                            for (key, value) in parameters {
                            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                            }
                            },
                            encodingCompletion: { (encodingResult) -> Void in
                            switch encodingResult {
                            case .Success(let upload, _, _):
                            upload.responseJSON { response in
                            if response.result.isSuccess || response.response?.statusCode == 200 {
                            completion(json: upload, error: nil)
                            } else {
                            dispatch_async(dispatch_get_main_queue()) {
                            completion(json: nil, error: response.result.error)
                            }
                            }
                            }
                            upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                            let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
                            onProgress(progress: progress)
                            }
                            case .Failure:
                            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                            break
                            }
                            }) }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 26 '17 at 8:28









                            Daniel KutaDaniel Kuta

                            1,5011021




                            1,5011021























                                1














                                func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
                                var headers = Alamofire.SessionManager.defaultHTTPHeaders
                                headers["Headerkey"] = "Headerkey"

                                Alamofire.upload(multipartFormData:
                                { (multipartFormData) in

                                if data != nil {
                                multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
                                }else{
                                multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
                                }

                                for (key, value) in jsonInput
                                {
                                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                                }
                                }, to:url, method: .post, headers: headers)
                                { (result) in
                                switch result {
                                case .success(let upload, _ , _ ):
                                upload.uploadProgress(closure:
                                { (progress) in
                                print(String(format:"%.0f%@",Float(progress.fractionCompleted)*100,"%")))

                                })

                                upload.responseJSON { response in
                                if showLoader == true
                                {
                                MBProgressHUD.hide(for: controller.view, animated: true)
                                }

                                completion(response)

                                }
                                case .failure(let encodingError):
                                print(encodingError.localizedDescription)

                                break
                                }
                                }
                                }





                                share|improve this answer






























                                  1














                                  func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
                                  var headers = Alamofire.SessionManager.defaultHTTPHeaders
                                  headers["Headerkey"] = "Headerkey"

                                  Alamofire.upload(multipartFormData:
                                  { (multipartFormData) in

                                  if data != nil {
                                  multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
                                  }else{
                                  multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
                                  }

                                  for (key, value) in jsonInput
                                  {
                                  multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                                  }
                                  }, to:url, method: .post, headers: headers)
                                  { (result) in
                                  switch result {
                                  case .success(let upload, _ , _ ):
                                  upload.uploadProgress(closure:
                                  { (progress) in
                                  print(String(format:"%.0f%@",Float(progress.fractionCompleted)*100,"%")))

                                  })

                                  upload.responseJSON { response in
                                  if showLoader == true
                                  {
                                  MBProgressHUD.hide(for: controller.view, animated: true)
                                  }

                                  completion(response)

                                  }
                                  case .failure(let encodingError):
                                  print(encodingError.localizedDescription)

                                  break
                                  }
                                  }
                                  }





                                  share|improve this answer




























                                    1












                                    1








                                    1







                                    func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
                                    var headers = Alamofire.SessionManager.defaultHTTPHeaders
                                    headers["Headerkey"] = "Headerkey"

                                    Alamofire.upload(multipartFormData:
                                    { (multipartFormData) in

                                    if data != nil {
                                    multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
                                    }else{
                                    multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
                                    }

                                    for (key, value) in jsonInput
                                    {
                                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                                    }
                                    }, to:url, method: .post, headers: headers)
                                    { (result) in
                                    switch result {
                                    case .success(let upload, _ , _ ):
                                    upload.uploadProgress(closure:
                                    { (progress) in
                                    print(String(format:"%.0f%@",Float(progress.fractionCompleted)*100,"%")))

                                    })

                                    upload.responseJSON { response in
                                    if showLoader == true
                                    {
                                    MBProgressHUD.hide(for: controller.view, animated: true)
                                    }

                                    completion(response)

                                    }
                                    case .failure(let encodingError):
                                    print(encodingError.localizedDescription)

                                    break
                                    }
                                    }
                                    }





                                    share|improve this answer















                                    func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
                                    var headers = Alamofire.SessionManager.defaultHTTPHeaders
                                    headers["Headerkey"] = "Headerkey"

                                    Alamofire.upload(multipartFormData:
                                    { (multipartFormData) in

                                    if data != nil {
                                    multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
                                    }else{
                                    multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
                                    }

                                    for (key, value) in jsonInput
                                    {
                                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                                    }
                                    }, to:url, method: .post, headers: headers)
                                    { (result) in
                                    switch result {
                                    case .success(let upload, _ , _ ):
                                    upload.uploadProgress(closure:
                                    { (progress) in
                                    print(String(format:"%.0f%@",Float(progress.fractionCompleted)*100,"%")))

                                    })

                                    upload.responseJSON { response in
                                    if showLoader == true
                                    {
                                    MBProgressHUD.hide(for: controller.view, animated: true)
                                    }

                                    completion(response)

                                    }
                                    case .failure(let encodingError):
                                    print(encodingError.localizedDescription)

                                    break
                                    }
                                    }
                                    }






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 23 '18 at 5:56

























                                    answered Nov 22 '18 at 12:19









                                    Sandeep KaliaSandeep Kalia

                                    295




                                    295






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34890922%2fmultipart-form-image-parameters-headers-post-request-with-alamofire-in-swift%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                        Alcedinidae

                                        RAC Tourist Trophy