1

I am trying to use Google Vision API and upload an image using their API to get analysis. I am using this php code:

<?php

include("./includes/common.php");
include_once("creds.php"); // Get $api_key
$cvurl = "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key;
$type = "LABEL_DETECTION";

//echo "Item is: " . $item;

//Did they upload a file...

$item = $_GET[item];



if($_FILES['photo']['name'])
{
}else{
echo "you did not upload image".
}

It always show "you did not upload image". And here's my Swift function where I upload the image:

func UploadRequest(img: UIImage, item: String)
    {

        let url = NSURL(string: "http://myurlhere")

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

        let boundary = generateBoundaryString()

        //define the multipart request type

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



        let image_data = UIImagePNGRepresentation(img)


        if(image_data == nil)
        {
            return
        }


        let body = NSMutableData()

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




        //define the data post parameter

        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 {
                //EZLoadingActivity.hide(success: false, animated: true)
                print("error")
                return
            }

            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(dataString)
            //EZLoadingActivity.hide(success: true, animated: true)
            self.dismissViewControllerAnimated(true, completion: nil)
        }

        task.resume()


    }

When I do print_r($_FILES), I get:

Array
(
    [file] => Array
        (
            [name] => image.png
            [type] => image/png
            [tmp_name] => /tmp/phplSB2dc
            [error] => 0
            [size] => 864781
        )

)
3
  • What happens if you do a print_r($_FILES)? Commented Aug 3, 2016 at 15:39
  • Here: Array ( [file] => Array ( [name] => image.png [type] => image/png [tmp_name] => /tmp/phplSB2dc [error] => 0 [size] => 864781 ) ) Commented Aug 3, 2016 at 15:41
  • Please edit your post to include any additional information you have to your question. Avoid adding this in the comments, as they are harder to read and can be deleted easier. The edit button for your post is just below the post's tags. Commented Aug 3, 2016 at 15:42

2 Answers 2

4

Your form data is currently submitting:

body.appendData("Content-Disposition:form-data; name=\"file\";...

And according to your print_r($_FILES), you should be using file instead of photo:

$_FILES['file']['name']

Also, you should be checking to make sure the file uploaded correctly using:

if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
    //File uploaded correctly
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I missed that string!
0
 func uploadMultipleIMAGE( APIStriing:NSString, dataString:NSString) -> Void
    {

//Here dataString is image binary data just append you your url and just pass the image it will handle.

        print("wscall URL string \(APIStriing)")
        print("Data string URL string \(dataString)")


        let postData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
        let postLength = "\(UInt(postData.length))"
        let request = NSMutableURLRequest()
        request.URL = NSURL(string: APIStriing as String)!
        request.HTTPMethod = "POST"
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = postData

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
            if error == nil {
               print("success")
            }
            else {
                let alert = UIAlertView(title: "Sorry For Inconvenience ", message: "Contact to Administration", delegate: self, cancelButtonTitle: "Ok")
                alert.show()
            }
        })
    }

Note:- when you convert image to binary data you need to handle special character. here you can handle special character. follow this step.

1.

let imgData = UIImagePNGRepresentation(image)
imgBase64String = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())

var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
  1. Create character handler class something like that.

    class handlecharacter: NSCharacterSet {

        func urlParameterValueCharacterSet() -> NSCharacterSet {
            let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
            characterser.addCharactersInString("-._~")
            return characterser
        }
    }
    

Now create function your class where you want to upload images

func percentEscapeString(imgstring:NSString) -> NSString
    {
        let handle = handlecharacter()
        return imgstring.stringByAddingPercentEncodingWithAllowedCharacters(handle.urlParameterValueCharacterSet())!

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.