在swift中使用AFNetworking上传多个图像

时间:2015-11-12 13:19:50

标签: php ios swift afnetworking

我想使用 swift 中的AFNetworking将多个图片上传到我的网站,但只会上传array中的最后一张图片。

swift 脚本:

let url = "http://pathtomysite"
        let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
        let request: NSMutableURLRequest = afHTTP.multipartFormRequestWithMethod("POST", URLString: url, parameters: nil, constructingBodyWithBlock: {(formData: AFMultipartFormData) in
            var i = 0
             for image in upImage {
                 let imageData  : NSData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
            formData.appendPartWithFileData(imageData, name: "uploaded_file", fileName: "imagex\(i)x.png", mimeType: "image/png")
            i++
            }
            }, error: nil)
        let managerS : AFURLSessionManager = AFURLSessionManager.init(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let uploadTask = managerS.uploadTaskWithStreamedRequest(request, progress: nil) { (response, AnyObject, error) -> Void in
            if (error != nil){
                print("error")
            }
        }
        uploadTask.resume()

php 脚本:

<?php
$dt = date("Ymdhis");
$fileInfo = pathinfo($_FILES['uploaded_file']['name']);
$file_path = "uploads/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {

     rename($file_path, 'uploads/' . $dt . '.' . $fileInfo['extension']);
} 

?>

1 个答案:

答案 0 :(得分:2)

试试这个:

foreach ($_FILES["uploaded_file"]["tmp_name"] as $index => $tmp_name) {
    $filePath = "uploads/" . basename($_FILES["uploaded_file"]["name"][$index]);
    if (move_uploaded_file($tmp_name, $filePath)) {
        // rename like you want to
    }
}

并将您的脚本更改为以下内容:

<script src="~/Scripts/angular-kendo.js"></script>

重要的是在您的上传代码中为 uploaded_file [] 添加括号。如果您不包含 [] ,则每个图片上传都会覆盖最后一个。

另一个重要的部分是脚本中的 foreach循环,它处理多个上传的图像而不是一个。