如何使用 Alamofire multipart 在参数中发送数组 [英] How to send array in params using Alamofire multipart

查看:28
本文介绍了如何使用 Alamofire multipart 在参数中发送数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Alamofire 将图像和文件上传到服务器.但是我面临着用图像发送参数数组的问题.但是当我在 params 中发送一个数组时,它会将数组转换为 JSON 字符串.但我想在 params 中发送一个数组,而不是 JSON 字符串.我搜索了很多,没有找到任何解决方案.所以请告诉我我的代码有什么问题.我正在使用以下代码:

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)
                   }
            }

推荐答案

这是将数组上传到 Alamofire 的静态方式.希望这对您有用.

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);
                }


        })

这篇关于如何使用 Alamofire multipart 在参数中发送数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆