Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)!,
        "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

like image 228
ashwin shrestha Avatar asked Jan 20 '16 03:01

ashwin shrestha


3 Answers

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)
    }
 })
}
like image 146
amit gupta Avatar answered Nov 18 '22 22:11

amit gupta


   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)
                    }
                }
            )
like image 1
Hrishikesh Menon Avatar answered Nov 18 '22 21:11

Hrishikesh Menon


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
            }
    }) }
like image 1
Daniel Kuta Avatar answered Nov 18 '22 22:11

Daniel Kuta