使用Swift不会在PHP中上载图像

时间:2016-08-03 15:36:44

标签: php swift

我正在尝试使用Google Vision API并使用其API上传图片以进行分析。我正在使用这个PHP代码:

<?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".
}

它始终显示&#34;您没有上传图片&#34;。这是我上传图片的Swift功能:

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


    }

当我print_r($_FILES)时,我得到:

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

)

2 个答案:

答案 0 :(得分:4)

您的表单数据目前正在提交:

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

根据您的print_r($_FILES),您应该使用file代替photo

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

此外,您应该检查以确保使用以下文件正确上传文件:

if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
    //File uploaded correctly
}

答案 1 :(得分: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()
            }
        })
    }

注意: - 当您将图像转换为二进制数据时,您需要处理特殊字符。在这里你可以处理特殊的角色。按照这一步。

1

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

var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
  1. 创建类似的字符处理程序类。

    类handlecharacter:NSCharacterSet {

        func urlParameterValueCharacterSet() -> NSCharacterSet {
            let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
            characterser.addCharactersInString("-._~")
            return characterser
        }
    }
    
  2. 现在在您要上传图像的类中创建函数

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