2

I'm trying to upload an array of pictures along with some parameters using Alamofire 4 and Swift 3.

The parameters seem to work because the update is done, but the images don't get to the server

In Postman I can do this fine with no problem:

Postman request sample

This is my code so far:

    let parameters = [
        "service_request_id" : servicesID,
        "status_id" : "4",
    ]
    Alamofire.upload(
        multipartFormData: { multipartFormData in
            
            for (key,value) in parameters {
                if let value = value as? String {
                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
            }
            
            for (image) in self.imagesArray {
                if  let imageData = UIImageJPEGRepresentation(image, 1) {
                    multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
                }
            }
    },
        to: ConnectionWS.UpdateServicesURL,
        method: .put,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                
                upload.uploadProgress(closure: { (progress) in
                    print(progress)
                })
                
                upload.responseJSON { response in
                    
                    // If the request to get activities is succesfull, store them
                    if response.result.isSuccess{
                        print(response.debugDescription)
                        alert.dismiss(animated: true, completion:
                            {
                                self.dismiss(animated: true, completion:
                                    {
                                        self.delegate?.statusChanged(IsFinish: false)
                                })
                                
                        })
                        
                        // Else throw an error
                    } else {
                        
                        
                        var errorMessage = "ERROR MESSAGE: "
                        if let data = response.data {
                            // Print message
                            let responseJSON = JSON(data: data)
                            if let message: String = responseJSON["error"]["message"].string {
                                if !message.isEmpty {
                                    errorMessage += message
                                }
                            }
                        }
                        print(errorMessage) //Contains General error message or specific.
                        print(response.debugDescription)
                    }
                    
                    alert.dismiss(animated: true, completion:
                        {
                            self.dismiss(animated: true, completion:nil)
                            
                    })
                }
            case .failure(let encodingError):
                print("FALLE ------------")
                print(encodingError)
            }
    }
    )

Am I doing something wrong?

Please help.

Community
  • 1
  • 1
  • http://stackoverflow.com/questions/39809867/alamofire-4-upload-with-parameters . Also, What do you want us to do to help you with specifically? Go through your code and try to find errors? Atleast put some effort to your question and tell us what **you have done so far** to research the problem and **what you have encountered**, logs, results, **responses**, crashes, errors, breakpoints etc. –  Feb 23 '17 at 22:58
  • Sorry @Sneak, I've already tried that. My problem is that I **haven't found any way to upload several images to the same parameter** (an array). I don't know if the `"name"` value should be `"image"`, `"image[]"` or `"image\(index)"` (the name of the array is `image`). I have tried all three ways and still haven't got the images to load to the server. – Reinaldo Verdugo Feb 23 '17 at 23:07
  • http://stackoverflow.com/questions/40262201/how-to-upload-multiple-images-in-multipart-using-alamofire http://stackoverflow.com/questions/40527140/mysql-and-swift-upload-image-and-file-would-it-be-better-to-use-alamofire http://stackoverflow.com/questions/28448837/uploading-multiple-image-files-with-swift There are some more threads with the same question. Check if any of those give you a hint. Full example codes for how to upload multiple files there too. –  Feb 23 '17 at 23:12
  • @Sneak thank you so much for you answer but it's still not working for me :( and when I try on Postman it works fine. – Reinaldo Verdugo Feb 24 '17 at 02:15

2 Answers2

4

So the error was from the server side, that had a very small size limit for images and that's why they weren't saving. I updated the compression for the JPEG images from

if  let imageData = UIImageJPEGRepresentation(image, 1)

to

if  let imageData = UIImageJPEGRepresentation(image, 0.6)

and now it's working fine.

Thank you @Sneak for your links.

  • 1
    I'm glad it solved for you :) BTW. Don't expect 0.6 to always return the correct size. You should instead implement a For loop that decreases the size according to your expected NSData length (Size) and returns your image when you reach the correct size that fits your need. Check other threads are made about this , basically just check the data size of the image, and compress further until you reach expected size. –  Feb 24 '17 at 18:47
0
for (key,value) in parameters {
                if let value = value as? String {
                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
            }

            for (image) in self.imagesArray {
                if  let imageData = UIImageJPEGRepresentation(image, 1) {
                    multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
                }
            }

//change this code to below 

for (key,value) in parameters {
                if let value = value as? String {
                    if value == "image" {
                        multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
                    } else {
                        multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)

                    }
                }
            }
Yogesh Makwana
  • 448
  • 4
  • 16