3

I am using Alamofire for uploading image and file to the server. But I am facing issue to send an array in parameters with the image. But when I send an array in params it converts the array in JSON string. But I want to send an array in params, not JSON string. I have searched a lot and did not find any solution. So please tell me what's wrong in my code. I am using below code:

let params = ["id":"112","arrayParam":["1232","12344","14325"]]

    let url = www.khxjjhdfsj.com/hsdgs
            let headers: HTTPHeaders = [
                /* "Authorization": "your_access_token",  in case you need authorization header */
                "Content-type": "multipart/form-data"
            ]
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                for (key, value) in params
                {
                     multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                }
                if let data = imageData
                {
                    multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/png")
                }
                if let data = pdfData
                {
                    multipartFormData.append(data, withName: "file", fileName: fileName, mimeType:"application/pdf")
                }
            }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
                switch result{
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        print("Succesfully uploaded")
                        if let err = response.error
                        {
                            onError?(err)

                            return
                        }



                    }
                case .failure(let error):
                    print("Error in upload: \(error.localizedDescription)")
                    onError?(error)
                   }
            }

3 Answers 3

2

You need to pass image parameter along with your other request parameters. Pass your array parameters like this in below code:

Alamofire.upload(
            multipartFormData: { multipartFormData in
                // Pass your image parameter in imgObj
                if  let imageData = UIImageJPEGRepresentation(imgObj, 1) {                        
                    multipartFormData.append(UIImagePNGRepresentation(imgObj)!, withName: "profile_image", fileName: "THDC", mimeType: "image/png")
                }
                // Send other request parameters
                for (key, value) in yourArray {
                    multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
                }
        },to: YourURL,headers:[:],
          encodingCompletion: { encodingResult in

            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    SVProgressHUD.dismiss()
                    debugPrint("SUCCESS RESPONSE: \(response)")

                    if let dicObj = response.result.value as? NSDictionary {
                        print(dicObj)

                        }
                }
            case .failure(let encodingError):
                SVProgressHUD.dismiss()
                print("ERROR RESPONSE: \(encodingError)")
            }
        }
        )
Sign up to request clarification or add additional context in comments.

9 Comments

Read my question. I want to send an array in parameters with the image.
attributes is your array. Pass your array instead of attributes
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key) // when I use this code. It converts the array into JSON array. But In my case, I want to send an array not JSON array.
your array contains dictionary or just strings ?
let array = ["1232","12344","14325"] // this type array
|
2

This is the static way to upload arrays to Alamofire. hope this may useful to you.

Alamofire.upload(multipartFormData: { (multipartFormData) in

            let imageData = UIImageJPEGRepresentation(imageUpload!, 0.5)

            multipartFormData.append(imageData!, withName: "profile_file", fileName: "file.png", mimeType: "image/jpg")

            for (key, value) in parameters {
                if  (value as AnyObject).isKind(of: NSMutableArray.self)
                {
                    let arrayObj = value as! NSMutableArray
                    //let data2 = NSData(bytes: &arrayObj, length: arrayObj.count)

                    let count : Int  = arrayObj.count

                    for i in 0  ..< count
                    {

                        let value = arrayObj[i] as! Int
                        let valueObj = String(value)

                        let keyObj = key + "[" + String(i) + "]"

                        multipartFormData.append(valueObj.data(using: String.Encoding.utf8)!, withName: keyObj)
                    }


                }
                else{
                    var valueStr = String()
                    if let param = value as? String{
                        valueStr = param
                    }else{
                        let valueInt = value as! Int
                        valueStr = String(valueInt)
                    }

                    multipartFormData.append((valueStr).data(using: String.Encoding.utf8)!, withName: key)
                }


            }



            }, to: urlString, encodingCompletion: { (encodingResult) in

                print("=====encodingResult=========",encodingResult)
                switch encodingResult {
                case .success(let upload, _, _):

                    upload.responseJSON(completionHandler: { (response) -> Void in


                        switch response.result {
                        case .success(let JSON):
                            print("JSON: \(JSON)")
                            onCompletion(JSON as? NSDictionary, nil)

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

                        }


                    })

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


        })

Comments

1

You need to append array with multipart data on the same key required, like in your code you need to change only given line of code:

  for (key, value) in params
        {
             // check the key on which key array is coming
            if key == "arrayParam" {

               let arrData =  try! JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                multipartFormData.append(arrData, withName: key as String)
            }
            else {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }

        }

Rest will be the same.

1 Comment

This is not the same, but may related, And I will try to keep this in mind for future. Thanks for response

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.