Multipart-форма (изображение,параметры,заголовки) Post-запрос с Alamofire в swift

во-первых, я хочу сказать, что я новичок в swift и немного знаю.Поэтому любая помощь будет одобрена. У меня есть форма multipart-data, которая имеет изображение (profile-image), несколько параметров(имя, фамилия) и заголовки (userid, hashCode). Я хочу отправить запрос POST для отправки формы.

я смог сделать запрос POST только с заголовками и другими параметрами, кроме 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
}

но как отправить изображение в виде файла (не base-64string), т. е. direct загрузка файлов с параметрами и заголовками.

спасибо заранее

3 ответов


можно использовать Alamofire 3.0+ код

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)
    }
 })
}

   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)
                    }
                }
            )

Я использую Alamofire (Swift 2.3) для отправки multipart с прогрессом.

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
            }
    }) }