Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload images to a server in iOS with Swift?

Tags:

ios

swift

It won't work, how to send an image from an iOS Swift app to my PHP server?

@IBAction func upload(sender: UIButton) {      var imageData = UIImageJPEGRepresentation(img.image, 90)    // println(imageData)     let url = NSURL(string:"http://www.i35.club.tw/old_tree/test/uplo.php")     //let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData     //var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 10)     var request = NSMutableURLRequest(URL: url)     request.HTTPMethod = "POST"      // set Content-Type in HTTP header     let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";     let contentType = "multipart/form-data; boundary=" + boundaryConstant     NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)     request.HTTPBody = imageData     // set data     //var dataString = "adkjlkajfdadf"     //let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)     //request.HTTPBody = requestBodyData       //      request.addValue(contentType, forHTTPHeaderField: "Content-Type")     request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")     //     // set content length      //NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)      var response: NSURLResponse? = nil     var error: NSError? = nil     let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)      let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)     println("API Response: \(results)") }  //take photo func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {       var selectedImage : UIImage = image      img.image = selectedImage     UIImageWriteToSavedPhotosAlbum(selectedImage, nil, nil, nil)     self.dismissViewControllerAnimated(true, completion: nil)  } 
like image 941
trees in Taiwan Avatar asked Oct 13 '14 08:10

trees in Taiwan


People also ask

How do I upload multiple images in Swift?

Swift 3 Just use "[]" with image upload param to make it array of images. The above code is to upload multiple images collection, according to the code you have images Data (Foundation. Data) in imagesData array.


1 Answers

I have taken the photo by user's choice and written code for swift 2 and iOS9

    func imageUploadRequest(imageView imageView: UIImageView, uploadUrl: NSURL, param: [String:String]?) {          //let myUrl = NSURL(string: "http://192.168.1.103/upload.photo/index.php");          let request = NSMutableURLRequest(URL:uploadUrl);         request.HTTPMethod = "POST"          let boundary = generateBoundaryString()          request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")          let imageData = UIImageJPEGRepresentation(imageView.image!, 1)          if(imageData==nil)  { return; }          request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)          //myActivityIndicator.startAnimating();          let task =  NSURLSession.sharedSession().dataTaskWithRequest(request,             completionHandler: {                 (data, response, error) -> Void in                 if let data = data {                      // You can print out response object                     print("******* response = \(response)")                      print(data.length)                     // you can use data here                      // Print out reponse body                     let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)                     print("****** response data = \(responseString!)")                      let json =  try!NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSDictionary                      print("json value \(json)")                      //var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err)                      dispatch_async(dispatch_get_main_queue(),{                         //self.myActivityIndicator.stopAnimating()                         //self.imageView.image = nil;                     });                  } else if let error = error {                     print(error.description)                 }         })         task.resume()       }       func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {         let body = NSMutableData();          if parameters != nil {             for (key, value) in parameters! {                 body.appendString("--\(boundary)\r\n")                 body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")                 body.appendString("\(value)\r\n")             }         }          let filename = "user-profile.jpg"          let mimetype = "image/jpg"          body.appendString("--\(boundary)\r\n")         body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")         body.appendString("Content-Type: \(mimetype)\r\n\r\n")         body.appendData(imageDataKey)         body.appendString("\r\n")          body.appendString("--\(boundary)--\r\n")          return body     }      func generateBoundaryString() -> String {         return "Boundary-\(NSUUID().UUIDString)"     }  }// extension for impage uploading  extension NSMutableData {      func appendString(string: String) {         let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)         appendData(data!)     } } 

--------- following code for the php side

<?php  $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $userId = $_POST["userId"];  $target_dir = "media";  if(!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }  $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);  if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir))  { echo json_encode([ "Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.", "Status" => "OK", "userId" => $_REQUEST["userId"] ]);  } else {  echo json_encode([ "Message" => "Sorry, there was an error uploading your file.", "Status" => "Error", "userId" => $_REQUEST["userId"] ]);  } 
like image 188
Vinod Joshi Avatar answered Sep 24 '22 18:09

Vinod Joshi