0

I am trying to upload an image to PHP server and image upload works fine. But I also want to send some parameters with the image file itself. Please help me with the below code on Swift 2.2 / iOS 9.3 for how am i suppose to add parameters along with the image file.

My PHP server code goes like:

        $info = pathinfo($_FILES['file']['name']);

    if ($info) {

        $imageName = md5(uniqid(rand(), true));

        $imageSize = getimagesize($_FILES['file']['tmp_name']);
        if ($imageSize === FALSE) {
            $newname = "default.jpg";
        }
        else {
            $ext = $info['extension']; // get the extension of the file
            $newname = $imageName.".".$ext;
        }
        $target = './images/'.$newname;    
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target))
{
            sendResponse(200, 'SUCCESS_IMAGE');
            return true;
} 

Swift code goes like:

func UploadRequest()
{
    let url = NSURL(string: "http://www.themostplayed.com/rest/upload.php")

    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    let boundary = generateBoundaryString()


    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    if (image.image == nil)
    {
        return
    }

    let image_data = UIImagePNGRepresentation(image.image!)


    if(image_data == nil)
    {
        return
    }


    let body = NSMutableData()

    let fname = "test.png"
    let mimetype = "image/png"




    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(image_data!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    request.HTTPBody = body



    let session = NSURLSession.sharedSession()


    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        print(dataString)

    }

    task.resume()


}


func generateBoundaryString() -> String
{
    return "Boundary-\(NSUUID().UUIDString)"
}
Ankit Khanna
  • 1,019
  • 2
  • 12
  • 22

1 Answers1

1

You can use you Alamofire to upload the image with parameter, for more information please find the below code.

func UploadRequest() {

   var parameters = [String:AnyObject]()//define parameter according to your requirement
   parameters = ["imageName":"Sample"]

   let URL = "http://www.themostplayed.com/rest/upload.php"
   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("success")

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

You can review the guideline and API information of Alamofire on below link.

URL : https://github.com/Alamofire/Alamofire

Hope it works for you.

Ramkrishna Sharma
  • 6,961
  • 3
  • 42
  • 51
  • Thanks for the help, are you sure that Alamofire library will not violate any of the Apple guidelines. My image upload code works fine even now, just want to add the parameters. I think if we can do it on my existing code, that would be superb!! – Ankit Khanna Apr 26 '16 at 17:06
  • Yes, it is not violate any of the Apple guideline. Also it is widely used for accomplished the web-service task. As before this library I had used the same code which you had shared for uploading the image but now I am use Alamofire api for it. – Ramkrishna Sharma Apr 26 '16 at 17:16