使用Alamofire通过参数数组上传多个文件

时间:2017-05-15 06:19:54

标签: ios swift swift3 alamofire image-uploading

我有参数数组和图像数组,每组参数包含一个且只有一个image.my code

let imgData = UIImageJPEGRepresentation(imageView.image!, 0.2)!
  Alamofire.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")

      for (key, value) in params {
        multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
      }
    },
                   to:URLUpdateProfile,
                   method:.post,
                   headers:headers)
    { (result) in
      switch result {
      case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
          print("Upload Progress: \(progress.fractionCompleted)")
        })

        upload.responseJSON { response in
          print(response.result.value)
        }

      case .failure(let encodingError):
        print(encodingError)  
      }
    }

使用此代码,我可以上传一个图像和一个参数。但我想发送数组中的参数和数组中的图像。是上传图像数组的参数数组的方法吗?如果是,如何跟踪图像和参数?

1 个答案:

答案 0 :(得分:1)

您可以在Operation上传每张图片及其参数。您的Operation应该是这样的:

class UploadImageOperation: Operation {
private var image: UIImage

init(withImage: UIImage) {
    super.init()

    image = withImage
}

override func main() {
    let imgData = UIImageJPEGRepresentation(image, 0.2)!
    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")

        for (key, value) in params {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    },
                     to:URLUpdateProfile,
                     method:.post,
                     headers:headers)
    { (result) in
        switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value)
                }

            case .failure(let encodingError):
                print(encodingError)  
            }
        }
    }
}

然后创建操作并将它们添加到队列中,如下所示:

let opQueue = OperationQueue()
opQueue.name = "imageUploadQueue"
opQueue.maxConcurrentOperationCount = 5 //number of images you want to be uploaded simultaneously
opQueue.qualityOfService = .background

for image in arrayOfImages {
    let uploadImageOperation = UploadImageOperation(withImage: image)
    opQueue.addOperation(uploadImageOperation)
}