2017-07-11 231 views
0

看來這個問題以前已經問過,但沒有答案對我很有幫助。我有一個應用程序,我創建了自己的ImagePicker以從用戶的相機膠捲中選擇多個圖像。我現在需要將這些圖像上傳到PHP腳本。當我只需要上傳一張圖片時,一切正常。事情是,我不知道如何更改我的代碼上傳多個圖像。從Swift上傳多張圖片到PHP

碼開始後(僅上傳相關的最重要的代碼)

let param = ["request":"uploadImagesAndParams", "someParam": self.txtSomeTextField.text!] 

     let boundary = generateBoundaryString() 

     request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") 

     //Here I am just selecting the first image in my UIImage array (selectedImages). I need to be able to select all of them and upload it. 
     let imageData = UIImageJPEGRepresentation((selectedImages?[0])!, 1) 

     if(imageData == nil) { return; } 

     request.httpBody = createBodyWithParameters(parameters: param, 
                filePathKey: "image", 
                imageDataKey: imageData! as NSData, 
                boundary: boundary) as Data 

代碼上傳

//Upload Function 
    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData { 
     let body = NSMutableData(); 

     if parameters != nil { 
      for (key, value) in parameters! { 
       body.appendString(string: "--\(boundary)\r\n") 
       body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") 
       body.appendString(string: "\(value)\r\n") 
      } 
     } 

     let filename = "user-profile.jpg" 
     let mimetype = "image/jpg" 

     body.appendString(string: "--\(boundary)\r\n") 
     body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n") 
     body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n") 
     body.append(imageDataKey as Data) 
     body.appendString(string: "\r\n") 



     body.appendString(string: "--\(boundary)--\r\n") 

     return body 
    } 



    func generateBoundaryString() -> String { 
     return "Boundary-\(NSUUID().uuidString)" 
    } 
+1

檢查這個問題,答案https://stackoverflow.com/questions/43972651/multiple-file-upload-with-array -of-參數-使用-alamofire/43972778#43972778。它應該給你如何實現這一目標的總體思路。 –

+0

這個問題是使用Alamofire。 –

+0

答案專注於'Operation'而不是'Alamofire'。你可以使用這個概念。其餘的是實現細節。 –

回答

0

我想通了,這樣做沒有進行操作的方式。下面的方法會將多個圖像上傳到PHP服務器。希望這可以幫助別人。

導入以下

import MobileCoreServices 

添加以下

var selectedImages: [UIImage]? 
var params: NSMutableDictionary = NSMutableDictionary() 

功能發出請求

function upload() { 
      // Retrieve server URL 
      let serverUrl = dbConn.OnlineDBConnectionString() 

      // Define server side script URL 
      let scriptUrl = serverUrl + "evalue8_api.php" 

      let myUrl = NSURL(string: scriptUrl); 

      let request = NSMutableURLRequest(url:myUrl! as URL); 
      request.httpMethod = "POST"; 

      //Note the [] after image 
      params = ["someVariable": self.txtMytextfield.text!, "image[]": selectedImages!] 

      let boundary = generateBoundaryString() 

      request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") 

      request.httpBody = createBodyWithParameters(parameters: params, boundary: boundary) as Data 

      _ = URLSession.shared.dataTask(with: request as URLRequest) { 
       data, response, error in 

       if error != nil { 
        print("Error=\(error!)") 
        return 
       } 

       do { 
        let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary 

        //print(parsedData) 
        let success = parsedData["response"] as! Bool 

        DispatchQueue.main.async { 
         if (success) { 
          //Do something 
         } 
        } 
       } catch { 
        print(error.localizedDescription) 
       } 
      }.resume() 
     } 

其他需要的功能

//Upload Function 
    func createBodyWithParameters(parameters: NSMutableDictionary?, boundary: String) -> NSData { 
     let body = NSMutableData() 

     if parameters != nil { 
      for (key, value) in parameters! { 

       if(value is String || value is NSString){ 
        body.appendString(string: "--\(boundary)\r\n") 
        body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") 
        body.appendString(string: "\(value)\r\n") 
       } 
       else if(value is [UIImage]){ 
        var i = 0; 
        for image in value as! [UIImage]{ 
         let filename = "image\(i).jpg" 
         let data = UIImageJPEGRepresentation(image,1); 
         let mimetype = mimeTypeForPath(path: filename) 

         body.appendString(string: "--\(boundary)\r\n") 
         body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n") 
         body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n") 
         body.append(data!) 
         body.appendString(string: "\r\n") 
         i += 1; 
        } 
        print(i) 
       } 
      } 
     } 
     body.appendString(string: "--\(boundary)--\r\n") 
     return body 
    } 

    func mimeTypeForPath(path: String) -> String { 
     let pathUrl = NSURL(string: path) 

     let pathExtension = pathUrl!.pathExtension 
     var stringMimeType = "application/octet-stream" 
     if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as CFString, nil)?.takeRetainedValue() { 
      if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { 
       stringMimeType = mimetype as NSString as String 
      } 
     } 
     return stringMimeType; 
    } 

    func generateBoundaryString() -> String { 
     return "Boundary-\(NSUUID().uuidString)" 
    } 

Extention需要

extension NSMutableData { 

    func appendString(string: String) { 
     let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) 
     append(data!) 
    } 
} 
0

這裏是Alamofire

的片段上傳多個圖像上傳

假設你有數組要上傳到服務

for aIndex in 0..<imgArray.count{ 
    if let imageData = UIImageJPEGRepresentation(imgArray[aIndex], 0.5) { 
     multipartFormData.append(imageData, withName: "Image\(aIndex).jpg") 
     } 
    } 

希望的圖像,這將幫助你

+0

我沒有使用Alamofire。你有沒有做過這個沒有Alamofire? –