Swift将多图像上传到PHP服务器

时间:2017-05-25 10:11:43

标签: php ios swift alamofire image-uploading

我想使用Alamofire Lib将多个图像上传到我的服务器,这是仅上传1张图片的问题。

我正在使用一个图像选择器,它返回一个名为

的UIImage数组

imagesdata

这是我的代码:

   @IBAction func uploadimages(_ sender: Any) {
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                for img in self.imagesdata{
                let imgdata = UIImageJPEGRepresentation(img, 1.0)
                    multipartFormData.append(imgdata!,withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
                    print("$$$$$$$$$$   :  \(imgdata!)")
                }
            },
            to: "http://localhost/maarathtest/MAPI/img_upload.php",
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
        }
        )


    }

和我的PHP:

<?php


$response = array();
if (empty($_FILES["image"])) {

    $response['File'] = "NOFILE";;


}else {

    $filename = uniqid() . ".jpg";
    // If the server can move the temporary uploaded file to the server
    if (move_uploaded_file($_FILES['image']['tmp_name'], "images/" . $filename)) {

        $response['status'] = "Success";
        $response['filepath'] = "https://serverName/MAPI/images/" . $filename;


} else{

    $response['status'] = "Failure";

  }
}



echo json_encode($response);
?>

我的控制台日志:

$$$$$$$$$$   :  5849743 bytes
$$$$$$$$$$   :  3253337 bytes
[Request]: POST http://localhost/maarathtest/MAPI/img_upload.php
[Response]: <NSHTTPURLResponse: 0x600000620940> { URL: http://localhost/maarathtest/MAPI/img_upload.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Length" = 101;
    "Content-Type" = "text/html";
    Date = "Thu, 25 May 2017 10:08:08 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.4.18 (Unix) OpenSSL/1.0.2h PHP/5.5.35 mod_perl/2.0.8-dev Perl/v5.16.3";
    "X-Powered-By" = "PHP/5.5.35";
} }
[Data]: 101 bytes
[Result]: SUCCESS: {
    filepath = "https://serverName/MAPI/images/5926ad083b770.jpg";
    status = Success;
}

更新:

我已经更改了我的代码,

 Alamofire.upload(
            multipartFormData: { multipartFormData in
                var count = 1
                for img in self.imagesdata{
                let imgdata = UIImageJPEGRepresentation(img, 1.0)
                multipartFormData.append(imgdata!,withName: "image\(count)", fileName: "image\(count).jpg", mimeType: "image/jpeg")
                count += 1

        }

        },...



<?php


$response = array();
if (empty($_FILES["image1"])) {

    $response['File1'] = "NOFILE";


}else {

    $filename = uniqid() . ".jpg";
    // If the server can move the temporary uploaded file to the server
    if (move_uploaded_file($_FILES['image1']['tmp_name'], "images/" . $filename)) {

        $response['status1'] = "Success";
        $response['filepath1'] = "https://serverName/MAPI/images/" . $filename;


} else{

    $response['status1'] = "Failure";

  }
}

if (empty($_FILES["image2"])) {

    $response['File2'] = "NOFILE";


}else {

    $filename = uniqid() . ".jpg";
    // If the server can move the temporary uploaded file to the server
    if (move_uploaded_file($_FILES['image2']['tmp_name'], "images/" . $filename)) {

        $response['status2'] = "Success";
        $response['filepath2'] = "https://serverName/MAPI/images/" . $filename;


} else{

    $response['status2'] = "Failure";

  }
}

echo json_encode($response);
?>

现在上传图片,但我不认为这是正确的方法,因为我不知道用户想要上传多少图片!

非常感谢任何想法,帮助,代码优化

感谢高级

2 个答案:

答案 0 :(得分:1)

我已经解决了这个问题,下面的代码希望能帮助一些人

斯威夫特:

 @IBAction func uploadimages(_ sender: Any) {


        Alamofire.upload(
            multipartFormData: { multipartFormData in
                var count = 1
                for img in self.imagesdata{
                let imgdata = UIImageJPEGRepresentation(img, 0.5)
                    // the name should be as array other wise want work
                multipartFormData.append(imgdata!,withName: "image[]", fileName: "image\(count).jpg", mimeType: "image/jpeg")
                count += 1

        }

        },
            to: "http://localhost/maarathtest/MAPI/img_upload.php",

            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
        }
        )

    }

PHP代码示例:

<?php


$response = array();
if (empty($_FILES["image"])) {

    $response['File1'] = "NOFILE";

}else {

    //$filename = uniqid() . ".jpg";

    // loop through files array from IOS app 
    foreach ($_FILES["image"]["tmp_name"] as $index => $tmp_name) {
    $filePath = "images/" . basename($_FILES["image"]["name"][$index]);
    if (move_uploaded_file($tmp_name, $filePath)) {

        // Images are stored in file path , do what ever is needed 

        $response['filepath'][$index] = $filePath;
    }
           $response['status'] = "Success";

}

}

echo json_encode($response);
?>

答案 1 :(得分:0)

使用以下代码将多个图像上传到您的服务器。我把它放在一个方法中,它接收NSMutableArrayUIImage个对象及其相应的名字在另一个数组中。如果需要,可以将NSMutableArray更改为Swift Array。成功上传后,将调用完成处理程序并根据您的响应返回映射对象:

代码:

public func executeMultipleImageUpload<T: Mappable>(type: T.Type, url: String, parameters: Dictionary<String, String>, images: NSMutableArray?, names: [String], view: UIView, completion: @escaping(_ result: DataResponse<T>?)-> Void) {

    //Calling Alamofire Upload method here...

    Alamofire.upload(multipartFormData: { multipartFormData in // This is first param, the part data itself

        if images == nil || images?.count == 0 {

            print("There are no images to upload..!!")

        } else {

            //Append image data from array of images to multipart form data

            var count = 1
            for image in images! {

                if let imageData = UIImageJPEGRepresentation(image as! UIImage, 0.76) {

                    multipartFormData.append(imageData, withName: names[count - 1], fileName: names[count - 1], mimeType: "image/jpeg")
                }

                count += 1

            }

        }

        //We are encoding the parameters to be sent here in the multipart as well..

        for (key, value) in parameters {

            multipartFormData.append((value.data(using: .utf8))!, withName: key)

        }}, to: url, method: .post, headers: ["": ""], //This is second param (to:)
        encodingCompletion: { encodingResult in // This is third param (encodingCompletion:)

            switch encodingResult {

            case .success(let upload, _, _):

                upload.response { [weak self] response in

                    guard self != nil else {

                        return
                    }

                    debugPrint(response)

                    }.validate().responseObject{

                        (response: DataResponse<T>) in

                            completion(response)


                }

            case .failure(let encodingError):

                print("error:\(encodingError)")

            }

    })

}