代码之家  ›  专栏  ›  技术社区  ›  Awais Fayyaz

在swift中使用多部分/表单数据上传带参数的图像

  •  -1
  • Awais Fayyaz  · 技术社区  · 7 年前

    我正在尝试将图像上载到 具体的 我的服务器的路径。该路径将由发送自的参数确定 multipart/form-data 要求

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

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

    我调用的API类似于

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

    upload\u图像的内容。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 并将图像传递给此函数 多部分/表单数据 要求

    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"
    

    这很好,但我需要根据发送自的参数确定此目录 多部分/表单数据 要求

    我的图像目录如下

    根目录 Root Directory

    子目录

    Child Directory

    孙子目录 Grand Child Directory

    因此,我希望能够传递一个路径(例如:“Brainplow/011113132018112642/”)作为请求的参数

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

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

    $target_dir = $_GET["path"];
    

    我可能不得不使用

    $target_dir = $_POST["path"];
    

    但我对PHP知之甚少。但可能还有另一个问题。但我的swift代码运行良好。只是我的形象不在我提供的道路上。

    任何帮助都将不胜感激

    2 回复  |  直到 7 年前
        1
  •  0
  •   Awais Fayyaz    7 年前

    修改了PHP函数

    更改了此行

    $target_dir = $_GET["path"];
    

    $target_dir = $_POST["path"];
    

    现在它正在工作

        2
  •  0
  •   Sandeep Kalia    6 年前

    使用参数上载多部分图像的完整解决方案

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