我是第一次使用Alamofire。我正在使用最新版本的Alamofire 1.3.1。我想在一个API调用中发送一幅图像,一幅视频和一些POST参数。我正在使用多部分表单数据。mutipart模块正在工作。我在发送额外的POST参数时遇到问题params。下面是我的代码。“ params”是包含额外参数的字典吗?如何在请求中附加这些POST参数。请帮忙
params
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): } } )
我找到了解决方案:)终于。
我们可以将数据作为多部分数据添加到请求中。
下面是我的代码。
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): } } )
编辑1: 对于那些试图发送数组而不是float,int或string的用户,他们可以在Json String中转换其数组或任何类型的数据结构,请将此JSON字符串作为普通字符串传递。并在后端解析此json字符串以获取原始数组