Search code examples
swiftalamofiremultipartform-dataimage-uploading

I'm trying to upload an array of images using Alamofire but getting error


I'm trying to upload an array of images to the server using Alamofire 4.8.2

Here is the function:

func uploadMultiplePhotos(centreId: Int, imagesArray: [UIImage]) {

    let parameters = ["ec_id": centreId, "uploaded_image": imagesArray] as [String : Any]
    Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in

        let count = imagesArray.count

        for i in 0..<count{

            multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")


        }
        for (key, value) in parameters {

            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
        print(multipartFormData)
    }, to: storeCentreImageURL) { (result) in

        switch result {
        case .success(let upload, _ , _):

            upload.uploadProgress(closure: { (progress) in

                print("uploding: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in

                print(response.result.value!)

            }

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

        }
    }

}

getting error in the line below:

multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")

Cannot invoke 'append' with an argument list of type '(UIImage, withName: String, fileName: String, mimeType: String)'


Solution

  • You need to convert the image to data

    imagesArray.indices.forEach {
      multipartFormData.append(imagesArray[$0].jpegData(compressionQuality:0.8)!, withName: "photo[\($0)]", fileName: "photo\($0).jpeg", mimeType: "image/jpeg")
    }