4

I'm having a problem with uploading multiple images in multiple array of images using multipart in Alamofire. Can any one help me? Thanks in advance!!

I am using the following code

let fileParameters = ["array_1": images1Array,
                      "array_2": images2Array]

func requestUpload(files: [String: Any]? = nil) {

Alamofire.upload( multipartFormData: { multipartFormData in
        if let files = files {
            for (key, value) in files {
                if let images = value as? [UIImage] {
                    for (index, image) in images.enumerated() {
                        let imageData = UIImageJPEGRepresentation(image, 1.0)
                        multipartFormData.append(imageData!, withName: "\(index)", fileName: "\(index).jpg", mimeType: "image/jpg")
                    }
                }
            }
        }
}, to: path , method: .post , headers: request.headers,
          encodingCompletion: { encodingResult in

            self.validatedData(of: encodingResult, handler: { (result, error) in
                handler(result, error)
            })
        })
}

So i want to know how to append multiple images in particular key.

Server Request something like this :

"array1":[
     {
        product_image: img1.jpg
     },
     {
        product_image: img2.jpg
     }
  ],
  "array2":[
     {
        product_image: img3.jpg
     }
  ]
1
  • can you show us Postman input for this request Commented May 30, 2018 at 14:39

2 Answers 2

1

Join imagesArrays using flatmap and loop through image.

let allImages = fileParameters.values.flatMap{$0}

allImages.enumerated().forEach {    
   multipartFormData.append(UIImagePNGRepresentation($1.values.first), withName: "product_image\($0)", fileName: "\($0).jpg", mimeType: "image/jpg")
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man you made my day with just one line of code "withName: "product_image[($0)]" :)
1

i hope this will work

make your key array type:-

 multipartFormData.append(imageData!, withName: "product_image[\(index)]", fileName: "\(index).jpg", mimeType: "image/jpg")

make your loops to create the index value in incremented order like 0,1,2,3.....N

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.