I am new to IOS n want to upload the image with parameters to server but it's not uploading. I tried a lot refer the alamofire and also base64 but nothing is working for me. Did I miss any thing, any help to understand this?
Thanks in advance. Please help me to resolve issue
Below is my code:
#IBAction func submitBtnClicked(_ sender: Any)
{
//parameters
var number: Int?
number = 47000482
var srNumber = String(format:"%d",number!)
var urlString: String = filePath!.absoluteString
var parameters = ["s_no":srNumber, "count":"1"]
let imgData = UIImageJPEGRepresentation(self.chosenImage!, 0.5)
print(parameters)
print(imgData)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData!, withName:"filestream", fileName:(self.filePath?.lastPathComponent)!, mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName:key)
}
}, to:"https://********************")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
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):
//self.delegate?.showFailAlert()
print(encodingError)
}
}
}
//MARK: - Multiple Images Uploading API Call
func serviceUploadMultipleImageData(model : UploadImageResponseModel,isLoader:Bool = true,name:String = "", loaderViewcontoller : UIViewController? = nil,url: String, method: HTTPMethod, InputParameter: Parameters?, ServiceCallBack: #escaping (_ Completion: ServiceResponseNormal, _ isSuccess:Bool)-> Void) {
let viewContoller = loaderViewcontoller
guard Reachability.isConnectedToNetwork() else {
Singleton.sharedSingleton.showPopup(title: "No Internet", message: HttpCode.NoInternetConnection.message(), image: nil, VC: viewContoller!)
ServiceCallBack(self.setCustomResponse(Code: HttpCode.NoInternetConnection.rawValue, Message: "No Internet Connection"),false)
return
}
if isLoader == true {
if viewContoller != nil {
ProgressHUD.startLoading(onView: (viewContoller?.view)!)
} else {
ProgressHUD.startLoading(onView: appDelegate.window!)
}
}
Alamofire.upload(multipartFormData: { (multipartFormData) in
for obj in model.arrImages{
multipartFormData.append(obj.imageData!, withName:obj.imgName, fileName: "", mimeType: "image/jpg")
}
for (key, value) in InputParameter! {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)!, withName: key)
}
}, to:url)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
model.progress = Progress.fractionCompleted
})
upload.responseJSON { response in
if isLoader == true {
if viewContoller != nil {
ProgressHUD.stopLoading(fromView: (viewContoller?.view)!)
}else {
ProgressHUD.stopLoading(fromView: appDelegate.window!)
}
}
if(response.result.isSuccess){
print(response)
do{
if response.data != nil{
var responseParsed = try JSONDecoder().decode(ServiceResponseNormal.self, from: response.data!)
if responseParsed.Code == "200"
{
responseParsed.Data = response.data
ServiceCallBack(responseParsed, true)
}
else
{
Singleton.sharedSingleton.showPopup(title: "Error", message: responseParsed.Message ?? "Error", image: nil, VC: viewContoller!)
ServiceCallBack(responseParsed, false)
}
}
}
catch let error {
print(error.localizedDescription)
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = "Response could not parsed"
ServiceCallBack(falilure, false)
}
}
else{
if let error = response.result.error{
let message = error.localizedDescription
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = message
ServiceCallBack(falilure, false)
Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
}
}
}
case .failure(let encodingError):
let message = encodingError.localizedDescription
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = message
ServiceCallBack(falilure, false)
Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
}
}
}
Firstly you need to add method type i.e .post or .put type with along with url then you will able to send the image data and also increase the timeout interval for request of session manager.session.configuration.timeoutIntervalForRequest = 120 If you have any query you reply me on same So I will try to resolve your problem.
class func requestForAPI(param:Dictionary<String, String>?, Url:String,image:UIImage,isShowLoader:Bool, headers:[String:String]?, completion: #escaping (_ result: AnyObject?, _ error: Error?) -> Void) {
let reach:Reachability = Reachability.forInternetConnection()
let netStatus:NetworkStatus = reach.currentReachabilityStatus()
if (netStatus == NotReachable)
{
NSUtility.shared().showMessage(title: "Alert!", body: "Please connect to the internet to continue", themetype: .error)
return
}
if isShowLoader == true{
APPDELEGATE?.showLoaderView()
}
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
let imageData = image.jpegData(compressionQuality: 0.8)
manager.upload(multipartFormData:
{
(multipartFormData) in
multipartFormData.append(imageData, withName: "file", fileName: "file.jpeg", mimeType: "image/jpeg") for (key, value) in param {
multipartFormData.append(value.data(using:String.Encoding.utf8.rawValue)!, withName: key)
}, to:URL(string: Url)!,method:.put, headers:headers)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON
{ response in
APPDELEGATE?.dismissLoader()
//print response.result
if response.result.value != nil
{
print (response.result.value as Any)
completion(response.result.value as AnyObject? , nil)
}
}
case .failure(let encodingError):
print(encodingError)
completion(nil, encodingError)
break
}
}}}
Related
I'm getting this message in console:
findWriterForTypeAndAlternateType:119: unsupported file format 'public.heic'
And getting empty JSON as response hence always showing Failed, Something went wrong
My code:
func alamofireMultipart2<T: Decodable>(urlString: String, body: [String: String], images: [(image: UIImage, param: String, fileName: String)], resultType: T.Type, completion: #escaping ([String: Any]?, String, String) -> Void) {
print("Inside Alamofire multipart")
guard let url = URL(string: urlString) else {
print("Invalid URL: " + urlString)
return
}
let header = ["Authorization" : "Bearer \(AppConfigs.accessToken)"]
Alamofire.upload(
multipartFormData: { multipartFormData in
print("body:")
body.forEach {
key, value in
print("key: \(key), value: \(value)")
multipartFormData.append(Data(value.utf8), withName: key)
return
}
images.forEach {
(image, param, filename) in
let imageData = image.jpegData(compressionQuality: 0.8)
print("Image Size = \(imageData?.count.byteSize)")
multipartFormData.append(imageData!, withName: param, fileName: filename, mimeType: "image/jpeg")
}
},
to: url,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("\n\nupload result, response: ")
print(response)
print("Error: ")
print(response.error ?? "null")
guard let data = response.data else {
print("response.data is nil")
return
}
let serializedData = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let parsedData = serializedData else {
print("Could not parse json")
completion(nil, "Failed", "Something went wrong")
return
}
let status = parsedData["status"] as? String ?? "Failed"
let message = parsedData["message"] as? String ?? "Something went wrong"
if status == "OK" {
print("Response parsed successfully! status is OK")
completion(parsedData, status, message)
} else {
print("status is not OK")
completion(nil, status, message)
}
}
case .failure(let encodingError):
print("Status Code: ")
print("Error!")
print(encodingError)
}
})
}
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)
}
}
}
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...
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
}
})
}
Firstly, i want to say i am new to swift, and know a little.So any help would be appriciated. I have a multipart-data form which has a image (profile-image), a few parameters (first-name, last-name) and headers(userid, hashCode). I want to send a POST request to submit the form.
I have been able to make POST request with only, headers and other parameters except image as:
let headers = [
"user_id": (Helper.getUserInfo()?.user_id)!,
"hash_code":(Helper.getUserInfo()?.hash_code)!,
]
let params = [
"name": self.name.text!,
"address":self.address.text!]
Alamofire.request(.POST, kFormUrl, parameters:params ,headers:headers).responseJSON { [weak self] response in
//working fine
}
But how to send image as a file (not base-64string) i.e. direct file upload with parameters and headers.
Thanks in advance
you can use Alamofire 3.0+ below code
func uploadImageAndData(){
//parameters
let gender = "M"
let firstName = "firstName"
let lastName = "lastName"
let dob = "11-Jan-2000"
let aboutme = "aboutme"
let token = "token"
var parameters = [String:AnyObject]()
parameters = ["gender":gender,"firstName":firstName,"dob":dob,"aboutme":aboutme,"token":token,"lastName":lastName]
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)
}
})
}
let userImageURL = NSURL(string: "your image url" as String)
let data = NSData.init(contentsOfURL: userImageURL!)
Alamofire.upload(
.POST,registerUrl!,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")
multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")
multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")
multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response)
let dict = response.result.value as! NSDictionary
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
I use Alamofire (Swift 2.3) to send multipart with progress.
func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
let headers:[String: String] = [:]
let router = URLRequest.URLRequest
let tuple = URLRequest.parameters
let parameters = tuple.0!
let imagesData = tuple.1
let url = router.URLString
self.manager!.upload(
.POST,
url,
headers: headers,
multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
for value in imagesData {
var mimeType = "video/jpg"
var bodyName = "images"
let filename = value.uniqueName
if value.mediaType == ReporterMediaType.image {
mimeType = "image/jpg"
bodyName = "images"
} else if value.mediaType == ReporterMediaType.video {
mimeType = "video/quicktime"
bodyName = "video"
} else if value.mediaType == ReporterMediaType.videoFrame {
mimeType = "image/jpg"
bodyName = "videoFrame"
}
multipartFormData.appendBodyPart(
data: value.data,
name: bodyName,
fileName: filename,
mimeType: mimeType)
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
},
encodingCompletion: { (encodingResult) -> Void in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
if response.result.isSuccess || response.response?.statusCode == 200 {
completion(json: upload, error: nil)
} else {
dispatch_async(dispatch_get_main_queue()) {
completion(json: nil, error: response.result.error)
}
}
}
upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
onProgress(progress: progress)
}
case .Failure:
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
break
}
}) }
func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: #escaping (_ result: DataResponse<Any>) -> Void) {
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["Headerkey"] = "Headerkey"
Alamofire.upload(multipartFormData:
{ (multipartFormData) in
if data != nil {
multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
}else{
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
}
for (key, value) in jsonInput
{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:url, method: .post, headers: headers)
{ (result) in
switch result {
case .success(let upload, _ , _ ):
upload.uploadProgress(closure:
{ (progress) in
print(String(format:"%.0f%#",Float(progress.fractionCompleted)*100,"%")))
})
upload.responseJSON { response in
if showLoader == true
{
MBProgressHUD.hide(for: controller.view, animated: true)
}
completion(response)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
}