Multipart-form(图像,参数,标题)使用Alamofire在swift中发布请求

时间:2016-01-20 03:14:16

标签: ios swift alamofire

首先,我想说我是新手,并且知道一点。所以任何帮助都会受到谴责。我有一个multipart-data表单,它有一个图像(profile-image),一些参数(first-name,last-name)和header(userid,hashCode)。我想发送一个POST请求来提交表单。

我已经能够只使用标题和其他参数发出POST请求,除了图像:

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)发送,即使用参数和标题直接上传文件。

提前致谢

4 个答案:

答案 0 :(得分:9)

您可以在代码

下使用 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)
    }
 })
}

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

答案 2 :(得分:1)

我使用Alamofire(Swift 2.3)发送多部分进度。

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

答案 3 :(得分: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
            }
        }
    }