Upload image to AWS S3 using alamofire upload - ios

I am trying to upload jpeg image to AWS using upload function. But i am getting the following error :
nw_endpoint_handler_add_write_request [29.1 52.92.250.6:443 failed socket-flow (satisfied)] cannot accept write requests
Some help would be of great use. Here is the code i am using (params is of type Data)
let request = Alamofire.upload(params, to: url, method: .put, headers: ["Content-Type":"image/jpeg"])
request.responseJSON { (responseJson) in
switch responseJson.result {
case .success:
print("Success: \(responseJson.result.value)")
break
case .failure:
print("Call failed: \(responseJson.result.value)")
break
default:
print("____")
}
}

Probably best to use Amazon's own SDK for doing this.
http://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3transfermanager.html

Try with this:
Swift 3.x:
func uploadImageWith(parameter params:Dictionary<String,String>,image:UIImage?,handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if image != nil {
if let imgData = UIImageJPEGRepresentation(image!, 0.5) {
multipartFormData.append(imgData, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
}
}, to: "http://") { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)")
handler(jsonDict)
print(jsonDict,(response.response!.statusCode))
}
else{
print(response.response!.statusCode)
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
print(response.response!.statusCode)
print_debug(error)
handler(nil)
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
}
Usage:
uploadImageWith(parameter: ["key":"value"], image: UIImage(named:"demo")) { (response) in
if response != nil {
print(response)
} else {
print("Something went wrong")
}
}

Related

how to upload image using alamofire and parameters in array form

i try many solution but give always this error when upload image on server using alomafire
Trailing closure passed to parameter of type 'FileManager' that does not accept a closure
let params: Parameters = ["name": "abcd","gender": "Male", "hobbies" : HobbyArray]
AF.upload(multipartFormData:
{
(multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.yourimageView.image!, 0.1)!, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg")
for (key, value) in params
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to: "\(BaseUrl)/save-beers" , headers:nil)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON
{ response in
//print response.result
if response.result.value != nil
{
let dict :NSDictionary = response.result.value! as! NSDictionary
let status = dict.value(forKey: "status")as! String
if status=="1"
{
print("DATA UPLOAD SUCCESSFULLY")
}
}
}
case .failure(let encodingError):
break
}
}
You can use this code for uploading Image
//MARK: - Upload image using alamofire with multiparts
func uploadImageAPIResponse(postPath:String,img: UIImage, parameters:NSDictionary, requestType: RequestType){
let imgData = img.jpegData(compressionQuality: 0.5)!
let headers: HTTPHeaders = ["Authorization": "Your_Auth if any otherwise remove Header from request"]
print("postPath:\(postPath)\nheaders:\(headers)\nparameters: \(parameters)")
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "file",fileName: "profile.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String)
} //Optional for extra parameters
},
to:postPath)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value as Any)
if response.result.isSuccess
{ let httpStatusCode: Int = (response.response?.statusCode)!
let data = (response.result.value as? NSDictionary)!
let meta = (data["meta"] as? NSDictionary)!
let code = meta["code"] as? Int ?? 0
print(data)
//if (data["success"] as? Bool)! {
print("httpCode" + String(httpStatusCode))
print("code" + String(code))
switch(httpStatusCode) {
case 200://operation successfull
if code == 401 {
let deleg = UIApplication.shared.delegate as! AppDelegate
User.defaultUser.logoutUser()
deleg.showLoginScreen()
}
self.delegate?.requestFinished(responseData: data, requestType: requestType)
break
case 204://no data/content found
self.delegate?.requestFinished(responseData: data, requestType: requestType)
break
case 401://Request from unauthorized resource
self.delegate?.requestFailed(error: "Request from unauthorized resource", requestType: requestType)
break
case 500://Internal server error like query execution failed or server script crashed due to some reason.
self.delegate?.requestFailed(error: "Internal server error like query execution failed or server script crashed due to some reason.", requestType: requestType)
break
default:
self.delegate?.requestFinished(responseData: data, requestType: requestType)
break
}
}
else
{
self.delegate?.requestFailed(error: (response.result.error?.localizedDescription)!, requestType: requestType)
}
}
case .failure(let encodingError):
print(encodingError)
self.delegate?.requestFailed(error: encodingError.localizedDescription, requestType: requestType)
}
}
}

How to convert UIImage to JPEG without loosing exif data?

I'm currently working on iOS applications and I'm using multipart image upload to uploading images to the server. Following is my image uploading method.
func uploadImageData(imageType:Int, uploadId:String, fileName:String, imageFile:UIImage, completion:#escaping (APIResponseStatus, ImageUploadResponse?) -> Void) {
let image = imageFile
let imgData = image.jpegData(compressionQuality: 0.2)!
let params = [APIRequestKeys.imageType:imageType, APIRequestKeys.uploadId:uploadId, APIRequestKeys.fileName:fileName] as [String : Any]
//withName is the post request key for the image file
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData, withName: APIRequestKeys.imageFile, fileName: "\(fileName).jpg", mimeType: "image/jpg")
for (key, value) in params {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
}
}, to: Constants.baseUrl + APIRequestMetod.uploadImageData, headers:self.getImageUploadHeaders())
{ (result) in
switch result {
case .success(let upload, _, _):
APIClient.currentRequest = upload
upload.uploadProgress(closure: { (progress) in
})
upload.responseObject {
(response:DataResponse<ImageUploadResponse>) in
switch response.result {
case .success(_):
completion(APIClient.APIResponseStatus(rawValue: (response.response?.statusCode)!)!, response.value!)
case .failure(let encodingError):
if let err = encodingError as? URLError, err.code == .notConnectedToInternet {
completion(APIClient.APIResponseStatus.NoNetwork, nil)
} else {
completion(APIClient.APIResponseStatus.Other, nil)
}
}
}
case .failure( _):
completion(APIClient.APIResponseStatus.Other, nil)
}
}
}
But for this implementation server is always sending exif data error. Following is the error that I'm getting.
exif_read_data(A029C715-99E4-44BE-8691-AA4009C1F5BD_FOTOPREGUNTA.ico): Illegal IFD size in
upload_image_xhr.php on line
The important thing is this service is working without errors in POSTMAN and android application as well. This error is only getting for my iOS implementation. My backend developer telling me that there is and exif data error in data that I'm sending and please verify the data from my side.
Anyone have an idea about this?
Thanks in advance.
I will make block function for Upload image to Server Using Multipart
//Here strUrl = YOUR WEBSERVICE URL
//postParam = post Request parameter i.e.
//let postParam : [String : Any] = [first_name : "name"]
//imageArray = image upload array i.e.
//var imageArray : [[String:Data]] = [["image_name" : YOUR IMAGE DATA]]
func postImageRequestWithURL(withUrl strURL: String,withParam postParam: Dictionary<String, Any>,withImages imageArray:[[String:Data]], completion:#escaping (_ isSuccess: Bool, _ response:NSDictionary) -> Void)
{
let requetURL = strURL
Alamofire.upload(multipartFormData: { (MultipartFormData) in
for (imageDic) in imageArray
{
for (key,valus) in imageDic
{
MultipartFormData.append(valus, withName:key,fileName: "file.jpg", mimeType: "image/jpg")
}
}
for (key, value) in postParam
{
MultipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
// MultipartFormData.append(value, withName: key)
}
}, usingThreshold: UInt64.init(), to: requetURL, method: .post, headers: ["Accept": "application/json"]) { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
let desiredString = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)
print("Response ====================")
print(desiredString!)
if let json = response.result.value as? NSDictionary
{
if response.response?.statusCode == 200
|| response.response?.statusCode == 201
|| response.response?.statusCode == 202
{
completion(true,json);
}
else
{
completion(false,json);
}
}
else
{
completion(false,[:]);
}
}
case .failure(let encodingError):
print(encodingError)
completion(false,[:]);
}
}
}
I Hope this will help...

iOS upload image as form Data Swift

I am using the below code to upload image, Its getting success but then in server side image is not opening.
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData{
multipartFormData.append(data, withName: "file", fileName: strDate, mimeType: "image/jpeg")
}
}, usingThreshold: UInt64.init(), to: stringUrl, method: .put, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error{
onError?(err)
return
}
onCompletion?(nil)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
}
Please help me in this what I am doing wrong here.
try with this code
func uploadeImage(image: Data, completion: #escaping (Bool) -> Void){
alamoFireManager!.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(image, withName: "file", fileName: "goalImage", mimeType: "image/png")
}, usingThreshold: UInt64.init(), to: "URL FOR YOUR END POINT", method: .post, headers: headers)
{ (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
completion(true)
}
case .failure( _):
completion(false)
}
}
}
for your image try whit this function
extension UIImage{
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
return jpegData(compressionQuality: jpegQuality.rawValue)
}
}
and finally, use like this code
let uploadImage = profilePicture.image.jpeg(.medium)
uploadImage(image: uploadImage){ (flag)
{
if flag
{
print("your image was uploaded")
}
}
Finally I got my mistake. I was doing image to data conversion two times. LOL
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
if key == "file" {
multipartFormData.append(value, withName: key as String)
} else {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
}
}, usingThreshold: UInt64.init(), to: stringUrl, method: .put, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error{
onError?(err)
return
}
onCompletion?(nil)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
}

How to upload multipart with this data

I want to send this data in the form of multipart to server with image/video. I have image/video data in byte data form (NSData or Data)
{"mediauploadata":
{
"type":"poll",
"server_token":"03f0e635b4c01b9f398de393259de8650b54c85c24f49998af50593643f559230d95e8e605612653769f4871b543e25d48bf",
"id":"105"
}
}
I have created a function for Multipart Upload using Alamofire.
Call this function passing Web service URL , Parameters and your image.
func WSPostAPIMultiPart(_ aStrULR:String,
param: [String: Any],
image : UIImage?,
controller: UIViewController,
successBlock: #escaping (_ response:[String : Any]?) -> Void,
failureBlock: #escaping (_ error: Error?) -> Void) {
var dictHeaders : HTTPHeaders = [String : String]()
if (Alamofire.NetworkReachabilityManager()?.isReachable)!{
Alamofire.upload(
multipartFormData: { MultipartFormData in
let JSONData: Data? = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
MultipartFormData.append(JSONData!, withName: "json")
if image != nil{
MultipartFormData.append(UIImageJPEGRepresentation(image!, 0.5)!, withName: "profile_image",fileName: "image.jpeg", mimeType: "image/jpeg")
// withName : You will pass the key name required by your server
}
}, to: aStrULR ,method : .post , headers : dictHeaders) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value {
let dictResponse = JSON(value).dictionaryObject
successBlock(dictResponse)
}
}
case .failure(let error):
failureBlock(error)
}
}
}else{
print("NO INTERNET CONNECTIVITY")
}
}
For Video: Just pass videoURL one extra parameter and append as :
MultipartFormData.append(videoUrl, withName: "profileVideo", fileName: "video.mp4", mimeType: "video/mp4")
Hope it helps :)
func uploadDataWith(parameter params:Dictionary<String,String>,data:Data?,isImage:Bool,handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if data != nil && isImage {
multipartFormData.append(data, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
if data != nil && !isImage {
multipartFormData.append(data, withName: "video_upload", fileName: "file.mp4", mimeType: "video/mp4")
}
}, to: "http://") { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)")
handler(jsonDict)
print(jsonDict,(response.response!.statusCode))
}
else{
print(response.response!.statusCode)
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
print(response.response!.statusCode)
print_debug(error)
handler(nil)
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
}

How to upload image using Alamofire with token&parameters?

I use Alamofire to upload images, however the upload is unsuccessful. I also bring token & parameters to server.
I don't know whether I add token & parameters correctly or not.
What's wrong with me to using Alamofire?
Have any suggestion?
Thanks.
func uploadWithAlamofire(image:UIImage, imageData:Data, imageUrl:URL) {
let parameters = ["avatar":imageData]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: user.id, fileName: "\(user.id).jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value, withName: key)
}
}, to: apiUrl , method: .put, headers: ["Authorization": "Bearer \(token)"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
photoImage = info[UIImagePickerControllerOriginalImage] as! UIImage
photoImageView.image = photoImage
let imageName:String = user.id + ".jpg"
let documentsPath = NSHomeDirectory().appending("/Documents/Icon/")
let imagePath = documentsPath.appending(imageName)
let imageUrl = URL(fileURLWithPath: imagePath)
print("imageUrl is here:\(imageUrl)")
let imageData:Data = UIImageJPEGRepresentation(photoImage, 0.001)!
do {
try imageData.write(to: imageUrl,options: .atomic)
} catch let error {
print(error)
}
uploadWithAlamofire(image: photoImage, imageData: imageData, imageUrl: imageUrl)
self.dismiss(animated: true, completion: nil)
}
Try this:
func uploadImageWith(param params:Dictionary<String,String>,image:UIImage?,handler:#escaping ((Dictionary<String,Any>?,Int) -> Void)) {
// let keyJson = "json".dataUsingEncoding(NSUTF8StringEncoding)!
print("Params:\(params)")
let BASE_URL = "http://"
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if image != nil{
let imgData = UIImageJPEGRepresentation(image!, 0.5)
if imgData != nil {
multipartFormData.append(imgData!, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
}
},
to: BASE_URL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print_debug("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict,(response.response!.statusCode))
}
else{
handler(nil,(response.response!.statusCode))
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil,(response.response!.statusCode))
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
USE
uploadImageWith(param: ["key":"value"], image: UIImage(name:"icon")) { (response, statusCode) in
print(response)
}
You have to pass the params and image object and you get the response as a Dictionary object in closure.
Use this function to upload image to the server with token and parameters
func uploadImageAndData(){
var parameters = [String:AnyObject]()
parameters = ["token": token,
"Name": Name]
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)
}
})}
Works for the Alamofire 3.0+

Resources