Reputation: 303
I am trying to make a server request using Alamofire. I need to send a file as a parameter.
var parameters: [String: AnyObject] = [:]
parameters["PAYLOAD"] = payloadString // String
parameters["FINGERPRINT"] = deviceUniqueIdString // String
I have a UIImage that I convert to NSData using UIImageJPEGRepresentation()
let imageData = UIImageJPEGRepresentation(myUIImage, 1.0)
parameters["IMAGE_FILE"] = imageData
Then, I use Alamofire to send the request:
Alamofire.request(.POST, apiURL, parameters: parameters).responseJSON { response in
}
This request works when I only send the payload and fingerprint parameters, but when I include the "IMAGE_FILE" parameter, the server returns error.
How should I send the UIImage?
Upvotes: 0
Views: 462
Reputation: 1370
In addition to @Fujia response, I wanted to add an example. This is the method I have been using recently for posting png files:
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)
}
}
)
}
Not the best solution, but it should give you a head start. Requires both SwiftyJSON and Alamofire 3.0 I believe. Gives you a completion handler for progress which can be useful. You should be able to find a more detailed answer here : Uploading file with parameters using Alamofire
Upvotes: 1
Reputation: 1242
Use Alamofire.upload(_:multipartFormData:encodingMemoryThreshold:encodingCompletion:)
instead of Alamofire.request
. You can add your parameters (including both strings and data) in the mutipart closure.
Upvotes: 1