Alamofire和PHP上传图片

时间:2018-09-14 14:17:32

标签: php swift alamofire

我正在尝试上载从iPhone画廊中选择的图像,我可以发送请求,但是这些图像永远无法从我的Web服务器上获取。我不知道问题是在请求还是在php中的脚本上。

swift 代码:

func enviarImg(){
    let imageParamName = "image"
    let parameters = ["chave": "valor"]

    Alamofire.upload(multipartFormData: { multipartFormData in
        // import image to request

        for imageData in self.imagens {
            let data = UIImageJPEGRepresentation(imageData, 1)

            multipartFormData.append(data!, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    },
                     to: url,
                     encodingCompletion: { encodingResult in
                        switch encodingResult {
                            case .success(let upload, _, _):
                                upload.responseJSON { response in

                                    print("success", response.result.value as Any)

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

和我的 php 代码:

<?php

     $i = 0;
     $result = array();

     while ($i <= 2){

        move_uploaded_file($_FILES[$i]["tmp_name"], $_FILES[$i]["name"]);

        $result["files"] = $_FILES[$i]["name"];

        $i++;

     }

     $result["message"] = "Success!";
     $result["post"] = $_POST;
     echo json_encode($result);
 ?>

来自php脚本的响应

success Optional({
  files = "<null>";
  message = "Success!";
  post =     (
  );
})

提前谢谢!

1 个答案:

答案 0 :(得分:2)

您的参数名称似乎不匹配:

您在Swift代码中使用的名称是“ image []”,但是在PHP代码内部却完全不同。

应该是

<?php
    $uploads_dir = '/uploads';
    foreach ($_FILES["image"]["error"] as $key => $error) {
         if ($error == UPLOAD_ERR_OK) {
             $tmp_name = $_FILES["image"]["tmp_name"][$key];

             $name = basename($_FILES["image"]["name"][$key]);
             move_uploaded_file($tmp_name, "$uploads_dir/$name");
         }
    }