以下代码是否是格式正确的POST请求?似乎整个内容都是通过URI而不是通过POST传递的。我对PHP和URL请求一般只有非常原始的理解,所以服务器端代码也包含在下面。
我注意到在尝试将base64编码图像(如下所示)上传到服务器时这是一个问题。提交请求后,服务器将返回一个错误,指出该URI超过了最大长度,这使我相信这不是提交POST请求的正确方法。如果图像只有10x10像素,整个过程都可以工作,但这并不能解决问题,这里的主要优先事项是理解正确的方法。
夫特
if let imageData = UIImagePNGRepresentation(self.image!) {
let encodedImage = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let dict = ["barcode":self.barcode, "imageData":encodedImage]
let json = JSONStringify(dict, prettyPrinted: false)
let jsonEncoded = CFURLCreateStringByAddingPercentEscapes(
nil, json, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue)
let server:String = GlobalVars.serverAddress
let phpFile:String = "/php/Inventory/UpdateItemImage.php"
let baseURL = NSURL(string: "\(server)\(phpFile)")
let url = NSURL(string: "?json=\(jsonEncoded)", relativeToURL: baseURL)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)
request.HTTPMethod = "POST"
let dataString = ""
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
do {
let reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
return true
} catch {
return false
}
}
PHP
<?php
// Setup DB connection etc..
//..
//Define passed variables
$json = $_GET['json'];
$json = stripslashes($json);
$fieldArray = json_decode($json);
$barcode = $fieldArray->{"barcode"};
$imageData = $fieldArray->{"imageData"};
// etc....
?>