2017-05-25 122 views
1

我想上传多张图片到我的服务器使用Alamofire Lib,它只上传1张图片的问题。快速上传多图片到PHP服务器

我使用的图像拾取返回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; 
} 

UPDATE:

我已经改变了如下我的代码,

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); 
?> 

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

任何想法,帮助,代码优化将是非常赞赏

在先进的感谢

+0

检查此 - https://stackoverflow.com/a/40907477/5172413 –

+0

其不工作我已检查我的PHP脚本的文件计数和其始终1 '$ response [“count”] = count($ _FILES ['image'] ['name']);' –

+0

您将需要以不同的变量接收每个图像文件。像 $ _FILES [ '图像1'], $ _FILES [ '图像2'],与 $ _FILES [ '图像3'] 或 您可以发送图像阵列和接收相同 –

回答

0

使用此下面的代码到多个图像上传到服务器。我已经把这个方法放入UIImage对象的NSMutableArray以及另一个数组中的对应名称。如果需要,您可以将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)") 

      } 

    }) 

} 
+0

根据你的代码,图像名称应该在将它们添加到** multipartFormData **时进行更改,所以如何在我的php脚本中接收这些文件名,请检查我的php脚本if(空($ _ FILES [“图像”])){'这不会工作 –

+0

我真的很困惑,我只上传1图像?或者我的php代码只处理1个文件? –

+0

我不确定你的PHP代码,因为我不是后端开发者,但你的AlamoFire代码似乎适用于多个图片。您可能需要检查您的后端代码。我的AlamoFire代码也是如此,但它包含其他参数以及图像。 –

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); 
?>