看來這個問題以前已經問過,但沒有答案對我很有幫助。我有一個應用程序,我創建了自己的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)"
}
檢查這個問題,答案https://stackoverflow.com/questions/43972651/multiple-file-upload-with-array -of-參數-使用-alamofire/43972778#43972778。它應該給你如何實現這一目標的總體思路。 –
這個問題是使用Alamofire。 –
答案專注於'Operation'而不是'Alamofire'。你可以使用這個概念。其餘的是實現細節。 –