使用 swift 中的 multipart/form 数据上传带有参数的图像

Uploading image with parameters using multipart/form data in swift

我正在尝试在我服务器的 特定 路径上传图像。该路径将由 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函数中,如果我将目录设置为constant字符串,它会保存在那个小路。就像我做下面的事情一样

$target_dir = "Brainplow"

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

发送的参数确定此目录

我的图片目录如下

根目录

子目录

孙目录

所以,我希望能够将路径(例如:"Brainplow/01113132018112642/")作为参数传递给请求

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

根据我的研究和努力,问题出在 PHP 函数上。所以也许不用

$target_dir = $_GET["path"];

我可能不得不使用

$target_dir = $_POST["path"];

但我PHP知道的不多。但也许还有另一个问题。但是我的 swift 代码运行良好。只是我的形象没有出现在我提供的路径中。

任何帮助将不胜感激

修改了PHP函数

更改了这一行

$target_dir = $_GET["path"];

$target_dir = $_POST["path"];

现在可以使用了

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

#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
            }
        }
    }