使用Swift通过PHP将图像上传到我的服务器

时间:2019-01-19 15:58:00

标签: ios swift alamofire

我正在使用下面的代码将图像上传到我的服务器,该代码发送了请求,但始终来自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的响应似乎缺少一些信息,但是我用需要的信息(名称和年龄)填充了两个字段。

我并不是缺少完整上传图像及其信息的人。

谢谢

2 个答案:

答案 0 :(得分:0)

在您的按钮单击事件中尝试此操作--->

    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)

答案 1 :(得分:0)

然后在您的代码中添加此功能...

func imagePickerController(_选择器:UIImagePickerController,didFinishPickingMediaWithInfo信息:[String:任何]){         如果让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)
}