【问题标题】:retrieve json data through $_POST from post request of alamofire swift3?通过 $_POST 从 alamofire swift3 的发布请求中检索 json 数据?
【发布时间】:2017-05-21 10:19:30
【问题描述】:

伙计们,我在使用 swift3 通过 alamofire 4 发布 json 数据时遇到问题,以及使用 php 在 XAMPP 服务器端检索 json 数据的问题。 我的 swift 3 代码确实在 XAMPP 触发了 php 脚本,但不知何故我无法通过 php 中的 $_POST 变量获取它 这是我的代码,

func uploadImage(image: UIImage){
    //Now use image to create into NSData format
    let imageData:NSData = UIImagePNGRepresentation(image)! as NSData      
    //convert the nsdata to base64 encoded string
       let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)
   // let parameters = ["image": strBase64] as Dictionary
    let parameters = ["image": strBase64]      
    print(strBase64) 
  Alamofire.request("http://localhost/Test/api/UploadPhoto.php",method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in            
    print(response)                   
                }   
}

这是我的服务器端代码(脚本确实是由 alamofire 的调用触发的,但不知何故我无法通过调用 $_POST["image"] 获取数据)

    <?php
//scripts below did get triggered, but can't get the json data through          calling $_POST["image"];
$imageString = $_POST["image"];
$filename_path = md5(time().uniqid()).".png"; 
$data = base64_decode($imageString);
file_put_contents('../AllImages/'.$filename_path, $data);
echo json_encode($_POST["image"]);
?>   

如果可能,请帮帮我,我已经挣扎了将近一个星期,但找不到很多线索 谢谢

【问题讨论】:

  • 您在 Chrome Inspector 中查看过网络请求吗?你看过var_dump($_POST);吗?
  • 我是这里的新手,但是我们如何在 xampp 服务器检索请求时检查它的控制台输出?我也尝试使用邮递员将 json 数据发送到 php 脚本,效果很好,但是当我从 ios 端发送请求时,它无法从 $_POST
  • XAMPP 不检索请求。你的浏览器可以。但是,您可以查看 apache 访问日志。然而,我的评论是关于 Chrome Inspector。这是谷歌Chrome浏览器中的一款软件。
  • 嗨 Daan,非常感谢您的帮助,我查看了 apache 的 access_log,这是我得到的:::::1 - - [06/Jan/2017:21:58:41 +1030] "POST /Test/api/UploadPhoto.php HTTP/1.1" 200 290 这对我来说没有多大意义
  • 对于我坚持使用您的浏览器,我深表歉意。我假设您正在构建一个 Web 应用程序。我看到你现在正在构建一个 iOS 应用程序。您也许可以使用error_log(json_encode($_POST)); 来查看发送到您的 PHP 脚本的数据。

标签: php json post swift3 alamofire


【解决方案1】:

我找到了解决这个问题的方法,基本上,我使用 urlsession.shared.datatask 来帮助我,而不是使用 alamofire 来处理发布请求, 这是我的ios端代码

     func uploadImage(image: UIImage, completionHandler: @escaping (String) ->()){

   // Now use image to create into NSData format
            let imageData:NSData = UIImagePNGRepresentation(image)! as NSData

            //convert the nsdata to base64 encoded string

               let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)
    // prepare json data
    let json: [String: Any] = ["image": strBase64]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    // create post request
    let url = URL(string: "http://10.10.10.72/Test/api/UploadPhoto.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    // insert json data to the request
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else {
                throw JSONError.ConversionFailed
            }

             completionHandler(json["sign"] as! String)

        } catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }

        }
    task.resume()
}

我使用字典来存储我的数据,并将其转换为json数据格式发送到服务器

     let json: [String: Any] = ["image": strBase64]
     let jsonData = try? JSONSerialization.data(withJSONObject: json)

然后在php端,我使用检索它

    $entityBody = file_get_contents('php://input');

,然后我从 json 解码,生成了一个数组,我可以通过引用图像来访问我的值,所以完整的 php 端代码如下:

    <?php
//get the posted json data
 $entityBody = file_get_contents('php://input');
//decode the json data
$decoded = json_decode($entityBody, TRUE);
$imageString = $decoded["image"];
//create a unique name for the image
 $filename_path = md5(time().uniqid()).".png"; 
//converted the image string back to image
 $data = base64_decode($imageString);
//put it on the desired location
file_put_contents('../AllImages/uploads/signature/'.$filename_path, $data);
 $response = array();
 //create the response 
 $response['sign'] = '../AllImages/uploads/signature/'.$filename_path;
 echo json_encode($response);
 ?>

请注意这里,我再次编码 json 数据以作为来自 php 的响应发送回我的 ios 端,并且您需要解码来自 json 的响应,所以完整的想法是如果您将值编码为 json 从一方面,您需要从另一端对其进行解码才能正确访问该值,如果我错了,请纠正我,我很高兴我的应用程序现在已经启动并运行所有请求:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 2020-09-30
    • 2014-07-06
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多