Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upload image to server using Alamofire

this is my code that I want to upload image to server using Alamofire, it not error but it can't push image to server. what should I do?

let url = URL(string: urlString)! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST"  let parameters = ["name": rname]  do {     urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) } catch {     print(error) }  urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")     let image = UIImage.init(named: "myImage")     let imgData = UIImageJPEGRepresentation(image!, 0.2)!   Alamofire.upload(multipartFormData: { MultipartFormData in          MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")       },with: urlRequest,encodingCompletion: { encodingResult in          switch encodingResult {          case .success(let upload, _, _):              upload.responseJSON { response in                  if let info = response.result.value as? Dictionary<String, AnyObject> {                      if let links = info["links"] as? Dictionary<String, AnyObject> {                          if let imgLink = links["image_link"] as? String {                             print("LINK: \(imgLink)")                         }                     }                 }              } case .failure(let error):                 print(error)         }     }) 
like image 961
Chea Sambath Avatar asked Nov 10 '16 04:11

Chea Sambath


People also ask

How do I upload files using Alamofire?

Here is a simple function that requires the target upload url, parameters, and imageData and returns the URLRequestConvertible and NSData that Alamofire. upload requires to upload an image with parameters. almost right, uploadData. appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.

What is the use of Alamofire in Swift?

Alamofire is an HTTP networking library written in Swift. Alamofire helps to improve the quality of code. It is a simpler way to consume REST services. Alamofire is the basic tool for hundreds of projects.

Is Alamofire asynchronous?

Everything with Alamofire is asynchronous, which means you'll update the UI in an asynchronous manner: Hide the upload button, and show the progress view and activity view. While the file uploads, you call the progress handler with an updated percent.


2 Answers

Try below code

 let image = UIImage.init(named: "myImage")  let imgData = UIImageJPEGRepresentation(image!, 0.2)!   let parameters = ["name": rname] //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:"mysite/upload.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.result.value)           }      case .failure(let encodingError):         print(encodingError)       } } 
like image 139
Ekta Padaliya Avatar answered Oct 14 '22 21:10

Ekta Padaliya


let params: Parameters = ["name": "abcd" "gender": "Male"] Alamofire.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:yourUrl,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     }    } 
like image 28
Chandan Taneja Avatar answered Oct 14 '22 21:10

Chandan Taneja