iOS upload image as form Data Swift - ios

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)
}
}
}

Related

Pattern cannot match values of type 'URLRequest'

I am trying to upload an image in Alamofire parameters. But I keep getting this error that wont let me compile. I am using swift 5.
Error
let image = profilePictureView.image!
let imageData = image.jpegData(compressionQuality: 0.50)
print(image, imageData!)
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: "file", fileName: "swift_file.png", mimeType: "image/png")
for (key, value) in estimatedParams {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
}
}, to: ServiceConstants.baseUrl+ServiceConstants.MD_UPDATE_PROFILE+"/\(userId)")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
print("uploading \(progress)")
})
upload.responseJSON { response in
//print response.result
}
case .failure( _): break
//print encodingError.description
}
}
You can use this function:
//MARK: - Upload Image
private func uploadUserImage(image: UIImage) {
if let imageData = image.jpegData(compressionQuality: 1.0) {
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "image" , fileName: "profile-image.png", mimeType: "image/png")
},
to: WebService.profileImageUploadURL, method: .post, headers: headers)
.downloadProgress { progress in
print(progress)
}
.response { response in
if response.response?.statusCode == 200 {
self.delegate?.uploadImageResponse(status: .success)
} else {
self.delegate?.uploadImageResponse(status: .failed)
}
}
}
}

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

Getting Error in post parameters with MultipartFormData using Alamofire Swift

I am unable to upload images to server getting. Showing upload progress upload.uploadProgress but after upload.responseJSON is nil error.
I have tried my best but couldn't solve the issue. Please anyone can help me out. What am I doing wrong? when I debug it { (result) in switch result { result is invalid.
Postman key: (parameters)
ImageList -- for images
ProjectUnitID -- 8568816
Swift Code:
if asset.type == .photo {
let displayImage = asset.fullResolutionImage!images?.append(d)
let token = UserDefaults.standard.string(forKey: "newToken")
let image = displayImage
let imgData = image.jpegData(compressionQuality: 0.2)!
let parameters = ["ProjectUnitId": 8568816]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "ImageList",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},to:"http://AddProjectUnitImages", headers: [ "Authorization":"Bearer \(String(describing: token))"]) { (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)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
Try this if this is a server error you will get the error here,
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(profileImg, withName: "user_image", fileName: "file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
} //}, to:url!,headers:nil)
}, to:url) { (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
print(progress)
})
//To check and verify server error
upload.responseString(completionHandler: { (response) in
print(response)
print (response.result)
})
upload.responseJSON { response in
switch response.result {
case .success:
print(response)
completion(response)
case .failure(let error):
print(error)
completion(response)
}
}
case .failure(_):
print(result)
// completion(responds)
}
}
Issue was at the back end side. Rectified and now my code works perfectly fine no issues.
Thanks everyone.

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
}
})
}

Upload image to AWS S3 using alamofire upload

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")
}
}

Resources