Alamofire和PHP上传图片

问题描述 投票:2回答:1

我正在尝试上传从iPhone图库中选择的图像,我可以发送请求,但图像永远不会在我的网络服务器上。我不知道问题是在请求上还是我在php中的脚本上。

这个快速的代码:

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 =     (
  );
})

提前致谢!

php swift alamofire
1个回答
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");
         }
    }
© www.soinside.com 2019 - 2024. All rights reserved.