【问题标题】:Upload image to my server via PHP using Swift使用 Swift 通过 PHP 将图像上传到我的服务器
【发布时间】:2019-01-19 15:58:00
【问题描述】:

我正在使用下面的代码将图像上传到我的服务器,代码发送请求但始终来自 API 的响应是(出现错误)。

在上传图片的同时,该图片的一些信息也会存储在mySql中。

这是我的代码,我使用的是 Xcode 10.1 和 Swift 4.2

 @IBAction func uploadImage(_ sender: Any) {

        self.showActivityIndicator()

        //Post URL
        let url = "https://website.com/folder/include/upload.php"

        //Getting text from textFiled!
        let name = nameField.text!
        let age = ageField.text!

        //Call Parameters
        let params: Parameters = ["name": name,"age": age]

        //Checking image place holder
        let image = UIImage(named: "map.png")

        //Checking if empty name or age fileds
        if name.isEmpty || age.isEmpty{

            self.hideActivityIndicator()
            myAlert(title: "Error", msg: "Make sure you enter all the required information!")
        }

        //Checking if image is not selected!!
        else if imageView.image == image
        {
            self.hideActivityIndicator()
            myAlert(title: "Error", msg: "Make sure you choose an image!")

        }else{

            let imageToUpload = self.imageView.image!

            Alamofire.upload(multipartFormData:
                {
                    (multipartFormData) in

                    multipartFormData.append(imageToUpload.jpegData(compressionQuality: 0.75)!, withName: "image", fileName: self.generateBoundaryString(), mimeType: "image/jpeg")
                    for (key, value) in params
                    {
                        multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                    }
            }, to:url,headers:nil)
            { (result) in
                switch result {
                case .success(let upload,_,_ ):
                    upload.uploadProgress(closure: { (progress) in
                        //Print progress
                        self.showActivityIndicator()
                    })
                    upload.responseJSON
                        { response in
                            //print response.result
                            if let result = response.result.value {

                                //Calling response from API
                                let message = (result as AnyObject).value(forKey: "message") as! String
                                let status = (result as AnyObject).value(forKey: "status") as! String

                                //Case Success
                                if status == "1" {

                                    self.hideActivityIndicator()
                                    print("Your Results are ====> ",result)
                                    self.myAlert(title: "Data Upload", msg: message)


                                    self.imageView.image = UIImage(named: "map.png")
                                    self.nameField.text = ""
                                    self.ageField.text = ""

                                }else{
                                    self.hideActivityIndicator()
                                    self.myAlert(title: "Error Uploading", msg: message)
                                }
                            }

                    }
                case .failure(let encodingError):
                    print(encodingError)
                    break
                }
            }
        }
    }

} 

这是PHP文件代码:

<?php

    include 'include/connect.php';

    //Get Param Data
    $name = $_POST["name"];
    $age = $_POST["age"];
    $xName = mysqli_real_escape_string($conn, $name);
    $xAge = mysqli_real_escape_string($conn, $age);



    //Results Array
    $result = array();

    //Image setup
    $uploads_dir = 'img';
    $tmp_name = $_FILES["image"]["tmp_name"];
    $image_name = basename($_FILES["image"]["name"]);
    $supported_image = array('gif','jpg','jpeg','png');

    $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); 


    if(empty($xName) || empty($xAge)|| empty($image_name))
    {

        // Send some dummy result back to the iOS app
        $result["message"] = "Sorry, there was an error uploading your file.";
        $result["status"] = "0";
        $result["post"] = $_POST;
        $result["files"] = $_FILES;


    }

    if (! in_array($ext, $supported_image)) 
    {

        // Send some dummy result back to the iOS app
        $result["message"] = "Sorry, Image extension is not Allowed!";
        $result["status"] = "0";
        $result["post"] = $_POST;
        $result["files"] = $_FILES;

    } 
    else
     {

         $query ="INSERT INTO images (name, age, image) VALUES ('$xName', '$xAge','$image_name')";

        if (mysqli_query($conn, $query)) {

            move_uploaded_file($tmp_name,"$uploads_dir/$image_name");

            // Send some dummy result back to the iOS app
            $result["message"] = "Data has been uploaded successfully.";
            $result["status"] = "1";
            $result["post"] = $_POST;
            $result["files"] = $_FILES;

        }      
     }

    echo json_encode($result);

?>

API 的响应似乎缺少一些信息,但我正在用所需的信息填充这两个字段,即(姓名和年龄)。

我没有完成图片及其信息的上传。

谢谢

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    在你的按钮点击事件中试试这个--->

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
        let addPhotos = UIAlertAction(title: "Choose Photo", style: .default) { (addPhoto) in
            self.imgPicker.sourceType = .photoLibrary
            self.imgPicker.allowsEditing = false
            self.present(self.imgPicker, animated: true, completion: nil)
        }
    
        let camera = UIAlertAction(title: "Camera Photo", style: .default) { (CameraPhoto) in
            self.imgPicker.sourceType = .camera
            self.imgPicker.allowsEditing = false
            self.present(self.imgPicker, animated: true, completion: nil)
        }
    
        let  cancel = UIAlertAction(title: "Cancel", style: .cancel) { (Cencel) in
            self.dismiss(animated: true, completion: nil)
        }
        alert.addAction(addPhotos)
        alert.addAction(camera)
        alert.addAction(cancel)
    
    
        self.present(alert, animated: true, completion: nil)
    

    【讨论】:

      【解决方案2】:

      然后在你的代码中添加这个函数...

      func imagePickerController(_picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { 如果让 img = info[UIImagePickerControllerOriginalImage] 为? UIImage{

              self.imgProfileImage.image = img
      
              let imgData = UIImageJPEGRepresentation(img, 0.5)!
      
              let parameters = [String : Any]
      
              Alamofire.upload(multipartFormData: { multipartFormData in
                  multipartFormData.append(imgData, withName: "Folder Name",fileName: "PicName.jpg", mimeType: "image/jpg")
                  for (key, value) in parameters {
                      multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                  } //Optional for extra parameters
              },
                               to:"Your API is Here.")
              { (result) in
                  switch result {
                  case .success(let upload, _, _):
      
                      upload.uploadProgress(closure: { (progress) in
                          print("Upload Progress: \(progress.fractionCompleted)")
                      })
      
                      upload.responseJSON { response in
                          print(response.result.value)
                      }
      
                  case .failure(let encodingError):
                      print(encodingError)
                  }
              }
      
          }
          self.dismiss(animated: true, completion: nil)
      }
      
      func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
          self.dismiss(animated: true, completion: nil)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-07
        • 2014-11-25
        • 2012-12-22
        • 2017-04-23
        • 1970-01-01
        • 2018-01-19
        • 1970-01-01
        • 2013-11-02
        相关资源
        最近更新 更多