2017-05-25 125 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); 
?>