使用Alamofire在iOS Swift中使用MultipartFormData发送POST参数

我第一次使用Alamofire。 我正在使用最新版本的Alamofire 1.3.1。 我想在一个API调用中发送一个图像,一个video和一些POST参数。 我正在使用多部分表单数据。 多部件模块正在工作。 我面临一个问题发送额外的POST参数params 。 以下是我的代码。 “params”是包含额外参数的字典吗? 如何在请求中附加这些POST参数。 请帮忙

  var fullUrl :String = Constants.BASE_URL + "/api/CompleteChallenge" var params = [ "authKey": Constants.AuthKey, "idUserChallenge": "16", "comment": "", "photo": imagePath, "video": videoPath, "latitude": "1", "longitude": "1", "location": "india" ] let imagePathUrl = NSURL(fileURLWithPath: imagePath!) let videoPathUrl = NSURL(fileURLWithPath: videoPath!) Alamofire.upload( .POST, URLString: fullUrl, // http://httpbin.org/post multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo") multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { request, response, JSON, error in } } case .Failure(let encodingError): } } ) 

我终于find了解决scheme:)

我们可以将请求中的数据作为multipartform数据添加。

以下是我的代码。

  Alamofire.upload( .POST, URLString: fullUrl, // http://httpbin.org/post multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo") multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video") multipartFormData.appendBodyPart(data: Constants.AuthKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"authKey") multipartFormData.appendBodyPart(data: "\(16)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"idUserChallenge") multipartFormData.appendBodyPart(data: "comment".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment") multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"latitude") multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"longitude") multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"location") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { request, response, JSON, error in } case .Failure(let encodingError): } } ) 

在Alamofire 4中, 添加文件数据之前添加正文数据非常重要!

 let parameters = [String: String]() [...] self.manager.upload( multipartFormData: { multipartFormData in for (key, value) in parameters { multipartFormData.append(value.data(using: .utf8)!, withName: key) } multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg") }, to: path, [...] 

这是我如何解决我的问题

 let parameters = [ "station_id" : "1000", "title": "Murat Akdeniz", "body": "xxxxxx"] let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1) Alamofire.upload( multipartFormData: { MultipartFormData in // multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg") for (key, value) in parameters { MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key) } MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg") MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg") }, to: "http://platform.twitone.com/station/add-feedback") { (result) in switch result { case .success(let upload, _, _): upload.responseJSON { response in print(response.result.value) } case .failure(let encodingError): break print(encodingError) } } 

Swift 3 / Alamofire 4.0 (已接受答案的附录)

要附加到Swift 3 / Alamofire 4.0中的MultipartFormData ,请使用MultipartFormData的以下方法:

 public func append(_ data: Data, withName name: String) { /* ... */ } 

而且,要将String转换为DataStringdata(using:)方法。 例如,

 multipartFormData.append("comment".data(using: .utf8)!, withName: "comment") 

正如在Swift 3.x上传带有参数的图片一样,我们可以使用下面的alamofire upload方法 –

 static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) { let imageData = UIImageJPEGRepresentation(imageFile , 0.5) Alamofire.upload(multipartFormData: { (multipartFormData) in multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg") for key in parameters.keys{ let name = String(key) if let val = parameters[name!] as? String{ multipartFormData.append(val.data(using: .utf8)!, withName: name!) } } }, to:inputUrl) { (result) in switch result { case .success(let upload, _, _): upload.uploadProgress(closure: { (Progress) in }) upload.responseJSON { response in if let JSON = response.result.value { completion(JSON) }else{ completion(nilValue) } } case .failure(let encodingError): completion(nilValue) } } } 

注意: – 另外如果我们的参数是密钥对数组,那么我们可以使用

  var arrayOfKeyPairs = [[String:Any]]() let JSON = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted]) let jsonPrasatation = String(data: JSON!, encoding: .utf8) 

为alamofire 4使用这个..

  Alamofire.upload(multipartFormData: { (multipartFormData) in multipartFormData.append(fileUrl, withName: "video") //fileUrl is your file path in iOS device and withName is parameter name }, to:"http://to_your_url_path") { (result) in switch result { case .success(let upload, _ , _): upload.uploadProgress(closure: { (progress) in print("uploding") }) upload.responseJSON { response in print("done") } case .failure(let encodingError): print("failed") print(encodingError) } }