我正在尝试使用Alamofire发出服务器请求。 我需要发送一个文件作为参数。
var parameters: [String: AnyObject] = [:]
parameters["PAYLOAD"] = payloadString // String
parameters["FINGERPRINT"] = deviceUniqueIdString // String
我有一个UIImage,我使用UIImageJPEGRepresentation()转换为NSData
let imageData = UIImageJPEGRepresentation(myUIImage, 1.0)
parameters["IMAGE_FILE"] = imageData
然后,我使用Alamofire发送请求:
Alamofire.request(.POST, apiURL, parameters: parameters).responseJSON { response in
}
当我只发送有效负载和指纹参数时,此请求有效,但是当我包含" IMAGE_FILE"参数,服务器返回错误。
我应该如何发送UIImage?
答案 0 :(得分:1)
使用Alamofire.upload(_:multipartFormData:encodingMemoryThreshold:encodingCompletion:)
代替Alamofire.request
。您可以在多部分闭包中添加参数(包括字符串和数据)。
答案 1 :(得分:1)
除了@Fujia回复,我想补充一个例子。这是我最近用于发布png文件的方法:
func WasperEntrepriseImageUploadCall(method: Alamofire.Method, imageData: NSData, parameters: [String: AnyObject]?, headers: [String: String]?, urlToPost: String,
progressionHandler: (bytesWritten: Int, totalBytesWritten: Int, totalBytesExpected: Int) -> (),
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject,NSError>, NSData?) -> ()){
Alamofire.upload(
method, urlToPost, headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "doesntmatter", mimeType: "image/png")
if let params = parameters{
for (key, value) in params {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
progressionHandler(bytesWritten: Int(bytesWritten), totalBytesWritten: Int(totalBytesWritten), totalBytesExpected: Int(totalBytesExpectedToWrite))
}
upload.response { response in
}.validate()
.responseJSON { response in
if let resp = response.response{
print(resp.statusCode)
print(response.result.value) // result of response serialization
}
completionHandler(response.request,response.response,response.result, response.data)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
不是最佳解决方案,但它应该为您提供一个良好的开端。我相信需要SwiftyJSON和Alamofire 3.0。为您提供有用的进度完成处理程序。您应该可以在此处找到更详细的答案:Uploading file with parameters using Alamofire