使用swift

时间:2018-04-11 09:37:40

标签: php ios swift multipartform-data

我正在尝试在服务器的特定路径上传图片。该路径将由multipart/form-data请求发送的参数确定。

问题:图片未上传到指定路径,而是上传到我的服务器的根目录。

我正在调用一个具有php函数的API,以将该图像保存到指定的路径。我认为PHP函数没有正确地从参数中获取路径。

我正在调用的API看起来像

https://storage.myWebsiteName.com/upload_image.php/

upload_image.php的内容

   <?php
header('Access-Control-Allow-Origin: *'); 

//Unable to get path parameter and store in @target_dir, instead this function stores image in root
$target_dir = $_GET["path"];


$name = basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $name;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image

$actual_name = strtolower(
    pathinfo(
            $_FILES["fileToUpload"]["name"],PATHINFO_FILENAME));


    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo $name;
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

?>

我从UIImagePickerController获取图像并将图像传递给此函数,该函数使multipart/form-data请求

func postImageToDB(image : UIImage) {

    let imagePostUrlStr =  "https://myWebsiteName.com/upload_image.php/"

    guard let imageData = UIImagePNGRepresentation(image) else {
      return
    }
    //want to save my image to this directory which is inside root
    let params = ["path" : "Brainplow/001243192018125835"]

    Alamofire.upload(multipartFormData: { (multiPartFormData: MultipartFormData) in
      //append path parameter
      for (key, value) in params {
        multiPartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
      }
      multiPartFormData.append(imageData, withName: "fileToUpload", fileName: "testfilename.png", mimeType: "image/png")

    }, to: imagePostUrlStr) { (result: SessionManager.MultipartFormDataEncodingResult) in
      switch result {
      case .success(request: let uploadRequest, _, _ ):


        uploadRequest.uploadProgress(closure: { (progress) in

          print("Upload Progress: \(progress.fractionCompleted)")

        })

        uploadRequest.responseString { response in
          print("printing response string")
          print(response.value as Any)
          print(response)
          print(response.result)

        }

      case .failure(let error):
        print(error.localizedDescription)
      }
    }


  }

注意:在php函数中,如果我将目录设置为常量字符串,它会保存在该路径中。就像我在下面做一些事情

$target_dir = "Brainplow"

工作正常,但我需要从multipart/form-data请求

发送的params中确定此目录

我的图片目录如下

根目录 Root Directory

儿童目录

Child Directory

Grand Child Directory Grand Child Directory

所以,我希望能够传递路径(例如:&#34; Brainplow / 01113132018112642 /&#34;)作为请求的参数

PHP函数应该从参数获取路径并将图像放在那里

根据我的研究和奋斗,问题在于PHP功能。所以也许不是使用

$target_dir = $_GET["path"];

我可能必须使用

$target_dir = $_POST["path"];

但我不太了解PHP。但也许还有另一个问题。但我的快速代码工作正常。只是我的形象不在我提供的路径中。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

修改了PHP函数

更改了这一行

$target_dir = $_GET["path"];

$target_dir = $_POST["path"];

现在正在运作

答案 1 :(得分:0)

完整的解决方案,可上传带有参数的多部分图片

#import Alamofire

func multipartImage(data:Data?, url:String,jsonInput:[String: String], completion: @escaping (_ result: DataResponse<Any>) -> Void) {

        Alamofire.upload(multipartFormData:
            { (multipartFormData) in

                if data != nil {
                    multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
                }else{
                    multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
                }


                for (key, value) in jsonInput
                {
                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
        }, to:url, method: .post, headers: headers)
        { (result) in
            switch result {
            case .success(let upload, _ , _ ):
                upload.uploadProgress(closure:
                    { (progress) in
                        //Print progress
                })

                upload.responseJSON { response in

                    completion(response)

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