Failing While uploading Images By Almofire - ios

I am uploading images in multi-part form data but was not succeed it throwing an error. but I'm trying in postman it succeeded .i don't know where I have done a mistake.i have attached postman screenshot for uploading response.please check it and I'm Using Almofire for responce.
func uploadimages() {
let url = ServiceUrl.Base + "ShopRegistration/ShopPicture"
print("URL === > \(url)")
print(self.imgData?.count)
var token :String = ""
if let strToken = Preference.GetString(key: UserDefaultsKey.Token) {
token = strToken
}
var RequestDist : NSDictionary = NSDictionary()
RequestDist = ["ShopId": "\(Preference.GetInteger(key: UserDefaultsKey.ShopID))"]
as NSDictionary;
print(RequestDist)
if(Reachability.isConnectedToNetwork())
{
Alamofire.upload(multipartFormData: { (multipartFormData) in
if self.imgData != nil && (self.imgData?.count)! > 0 {
for dataImg in (self.imgData)! {
//shopImage
multipartFormData.append(dataImg, withName: "shopImage", fileName: "uploaded_file.jpeg", mimeType: "image/jpeg")
}
}
for (key, value) in RequestDist {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String )
}
print("Request ===>>> /n \(multipartFormData.contentType)")
}, to:url,headers :["authToken" : token])
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("\n")
print(Progress.fractionCompleted)
})
upload.responseJSON { response in
if(response.result.isSuccess){
print("\n\n")
print("\(response.result.isSuccess)")
print("\n\n")
print(response.result)
print("\n\n")
print(response)
print("\n\n")
appDelegate.window?.rootViewController?.view.makeToast(message: "Images added sucessfully")
let datastring = NSString(data:response.data!, encoding:String.Encoding.utf8.rawValue) as String?
print("Response:::>>>> \(String(describing: datastring))")
if let intShopID : Int = Preference.GetInteger(key: UserDefaultsKey.ShopID) {
self.getShopImagesCall(intshopID: intShopID)
}
}else{
appDelegate.window?.rootViewController?.view.makeToast(message: AppMessage.getErrorInResponse)
}
}
case .failure(let encodingError):
appDelegate.window?.rootViewController?.view.makeToast(message: AppMessage.getErrorInResponse)
break
}
}
}
}

for JPEG image on network use
let imageData = UIImageJPEGRepresentation(img, 0.5) and at body
multipartFormData.append(dataImg, withName: "shopImage", fileName: "uploaded_file.jpeg", mimeType: "image/jpeg").
for PNG image
let image = UIImagePNGRepresentation(pickedImage) and at body
multipartFormData.append(dataImg, withName: "shopImage", fileName: "uploaded_file.png", mimeType: "image/png").

Related

Uploading image from ImageVIew to remote server

I am trying to upload an image from a ImageView to a remote server.
This is my code:
func subir_imagen(){
let image = self.foto.image
let imgData = image!.jpegData(compressionQuality: 1)!
let parameters = ["name": "jogua"] //Optional for extra parameter
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
} //Optional for extra parameters
},
to:"https://.../subir_foto_dispositivo.php")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
This is the file subir_foto_dispositivo.php:
// Save the image file
move_uploaded_file($_FILES["image"]["tmp_name"], $_FILES["image"]["name"]);
// Send some dummy result back to the iOS app
$result = array();
$result["user"] = $user;
$result["message"] = "Success!";
$result["files"] = $_FILES;
$result["post"] = $_POST;
echo json_encode($result);
And this is the output in debugger when uploading an image:
Upload Progress: 0.21640112366409928
Upload Progress: 0.4362101390394442
Upload Progress: 0.6628349378372804
Upload Progress: 0.8485650361001688
Upload Progress: 1.0
SUCCESS: {
files = {
fileset = {
error = 0;
name = "file.jpg";
size = 9615058;
"tmp_name" = "/tmp/phpH6Au4W";
type = "image/jpg";
};
};
message = "Success!";
post = {
name = jogua;
};
user = "<null>";
}
I am not getting any warning or error, but the image is not uploaded to the server, at least I can't find it in the folder.
I guess I am missing something.
func requestPostURLForUploadImage(success:#escaping (Dictionary<String,Any>) -> Void, failure:#escaping (Error) -> Void){
var image = self.foto.image
var strUrl = "http://103.51.0.xxx/papp_name/index.php/api/" // your server url here where image needs to upload
Alamofire.upload(multipartFormData: { multipartFormData in
let imgData = image.jpegData(compressionQuality: 0.2)
multipartFormData.append(imgData, withName: "image_one",fileName:"uploadimageName", mimeType: "image/jpg")
}, to: strUrl)
{ (result) in
switch result {
case .success(let upload, _ ,_ ):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
let resJson = response.result.value
if resJson != nil{
let res = resJson as! Dictionary<String, String>
if res.count > 0 {
success(resJson as! Dictionary<String, String>)
}
}
else {
print("Response not found")
}
}
case .failure(let error):
failure(error)
}
}
}

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...

how to upload image,pdf,audio,video and any file system from iphone local memory to server(API)

I have to upload any kind of file system from local phone memory to API given.Is there a simple way to that please help.
You can use Alamofire library.
https://github.com/Alamofire/Alamofire
Alamofire.upload(multipartFormData: { (multipartFormData) in
if let parameters = parameters {
for (key, value) in parameters {
if let value = value as? String {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}else if let _image = value as? UIImage, let image = _image.resized(toWidth: 500) {
if let jpegData = image.jpegData(compressionQuality: 0.5) {
multipartFormData.append(jpegData, withName: key, fileName: "post.jpeg", mimeType: "image/jpeg")
}else if let pngData = image.pngData() {
multipartFormData.append(pngData, withName: key, fileName: "post.png", mimeType: "image/jpeg")
}
}else {
multipartFormData.append(Data(from: value), withName: key)
}
}
}
}, usingThreshold: UInt64.init(), to: urlString, method: method, headers: headers, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let responseData = response.result.value as? NSDictionary {
completion(responseData, response.data, response.result)
}else if let responseData = response.result.value as? [String: Any] {
completion(responseData as NSDictionary, response.data, response.result)
}else {
completion([:], nil, response.result)
}
}
break
case .failure(let encodingError):
completion([:], nil, .failure(encodingError))
break
}
})

Not able to upload camera images using Almofire multipart

I have to upload images, audio, documents. I'm using Alamofire to upload. Everything is uploaded including gallery images like screenshots, but pictures taken from camera are not getting uploaded.
Here's my code:
func requestUploadFileWithMultipart(connectionUrl: String, param : [String: AnyObject], filePath: String?, _ callBack: #escaping (_ data: DataResponse<Any>?, _ error:Error?) -> Void) {
let URLString = MainURL + connectionUrl
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
let stringValue = "\(value)"
multipartFormData.append(stringValue.data(using: String.Encoding.utf8)!, withName: key)
print("Key: \(key), Value: \(stringValue)")
}
if filePath != "" {
do {
var fileData = try Data(contentsOf: URL(string: filePath!)!)
let ext = URL(fileURLWithPath: filePath!).lastPathComponent.components(separatedBy: ".").last
let mime = filePath?.mimeTypeForPath()
let fileName = "\(Date().timeIntervalSince1970)".components(separatedBy: ".").first
multipartFormData.append(fileData, withName: "file", fileName: "\(fileName ?? "file").\(ext ?? "")", mimeType: mime ?? "")
} catch {
print("error loading file in multipart")
}
}
}, to:URLString) { (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)
callBack(response, nil)
}
case .failure(let encodingError):
print(encodingError)
callBack(nil, encodingError)
}
}
}
Image compression worked for me. May be large files were no uploading.
Please try below code, I am using this code in my one of project. But make sure that API is suitable for multipart uploading.
Alamofire.upload(multipartFormData: {
multipartFormData in
if let img = image {
if let imageData = img.jpegData(compressionQuality: 0.4) {
multipartFormData.append(imageData, withName: "cmt_img", fileName: "\(Date()).jpg", mimeType: "image/jpg")
}
}
do {
let theJSONData = try JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions(rawValue: 0))
multipartFormData.append(theJSONData, withName: "data")
} catch {}
},usingThreshold: 0 ,to: baseURL + URLS.AddComment.rawValue, headers: appDelegate.headers, encodingCompletion: {
encodingResult in switch encodingResult {
case .success(let upload, _, _):
upload.responseObject(completionHandler: { (response: DataResponse<AddCommentData>) in
SVProgressHUD.dismiss()
if (response.result.value != nil) {
showAlert(popUpMessage.uploadingSuccess.rawValue)
}
else {
showAlert(popUpMessage.someWrong.rawValue)
}
})
break
case .failure(let encodingError):
SVProgressHUD.dismiss()
print(encodingError)
break
}
})
}

Alamofire multipart upload giving error

I am trying to upload an image to server using Alamofire Multipart Form data however upon execution iam getting error as
exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber
dataUsingEncoding:]: unrecognized selector sent to instance
0x1669e250'
in the line
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
below is my full code
guard let image = selectedImage else {
return
}
let heightInPixels = Int(image.size.height * image.scale)
let widthInPixels = Int(image.size.width * image.scale)
let parameters: Parameters = ["user_id": Utility().getBearerToken(),"description": descriptionTextView.text ?? "",
"lat": self.lat ?? "" , "long":self.long ?? "" ,
"location_name": locationTextView.text ?? "" ,
"height": heightInPixels, "width": widthInPixels];
// let parameters: Parameters = ["user_id": Utility().getBearerToken()];
print(parameters)
Alamofire.upload(multipartFormData: { MultipartFormData in
for (key, value) in parameters {
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
}
let imgData = UIImageJPEGRepresentation(image,1)
MultipartFormData.append(imgData!, withName: "file", fileName: "upload.jpg", mimeType: "image/jpeg")
}, to: "http://server.com/upload.php") { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseString { response in
print(response.result.value!)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
I tried with MultipartFormData.append(value.data(using: .utf8)!, withName: name!) but it says value has no member data
Try this below func, it is working.
func uploadImage(urlString : String , image : UIImage, param : [String : Any], completionHandler : #escaping ( _ result : Any?) -> ()) {
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
print("Could not get JPEG representation of UIImage")
return
}
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
multipartFormData.append(imageData,
withName: "image",
fileName: "image.jpg",
mimeType: "image/jpeg")
},
to: urlString,
headers: ["Authorization": "Basic xxx"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
}
upload.validate()
upload.responseJSON { response in
completionHandler(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
completionHandler(nil)
}
})
}
Here is the function for upload video and image with your other API Parameters.
func uploadWithAlamofire(Parameters params : [String: Any]?,ImageParameters imgparams : [NSObject : AnyObject]?,VideoParameters vidoparam : [NSObject : AnyObject]?,Action action : NSString, success: #escaping (AnyObject) -> Void, failure: #escaping (AnyObject) -> Void)
{
var base_url = BASEURL
base_url.append(action as String)
print(base_url)
var headers : HTTPHeaders = [:]
if let token = UserDefaults.standard.value(forKey: "webToken"){
headers = ["JWT-Authorization": "Bearer \(token)"]
}
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if vidoparam != nil{
for (key, value) in vidoparam! {
multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
var dictonary:NSDictionary?
if let data = responseString?.data(using: String.Encoding.utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?
if dictonary != nil{
if dictonary?.value(forKey: "status_code") as! String == "200"{
return success(dictonary!)
}else{
print(dictonary?.value(forKey: "status_code")! as Any)
let errorMsg : Any = Int(dictonary?.value(forKey: "status_code") as Any)
utility.showAlertWithStatusCode(code: errorMsg)
}
}
} catch let error as NSError {
print(error)
}
}
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}

Resources