swiftalamofiremultipartform-data

How to upload array or list of files (images) with Alamofire


I am using the following code to upload an image to server and it is working fine but i need to upload a array or list of images against one parameter (i.e "hunter_pictures")

Alamofire.upload(multipartFormData: { multipartFormData in  
   multipartFormData.append(UIImageJPEGRepresentation(spottingImage, 1)! , withName: "hunt_pictures", fileName: "user.jpg", mimeType: "image/jpeg")
   multipartFormData.append((userID.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "user_id")
                  },
                             to: url,
                            encodingCompletion: { encodingResult in
                                switch encodingResult {
                                case .success(let upload, _, _):

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

                                }
                        })

Solution

  • @maxwel's answer worked just one modification just add file format in fileName "hunter_picture.jpg". Added .jpg and it worked

    Alamofire.upload(
        multipartFormData: { multipartFormData in
        multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")
    
           for (index,image) in self.spottingImages.enumerated() {
              if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg")  }
                                        }
        },
                    to: url,
                    encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            print(upload)
                        case .failure(let encodingError):
                            print(encodingError)}
                })