如何使用Alamofire Multipart在参数中发送数组

时间:2018-07-16 11:09:51

标签: ios swift api alamofire multipartform-data

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

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 个答案:

答案 0 :(得分:1)

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

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


        })

答案 1 :(得分:1)

您需要将image参数与其他请求参数一起传递。在下面的代码中像这样传递您的数组参数:

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

答案 2 :(得分:1)

您需要在需要的同一键上添加包含多部分数据的数组,就像在代码中一样,您只需要更改给定的代码行即可:

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

        }

其余部分相同。