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

问题描述 投票:0回答:3

我正在使用 Alamofire 将图像和文件上传到服务器。但我面临着与图像一起发送参数数组的问题。但是当我在 params 中发送数组时,它会将数组转换为 JSON 字符串。但我想在 params 中发送一个数组,而不是 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)
                   }
            }
ios swift alamofire multipartform-data
3个回答
2
投票

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

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
投票

这是将数组上传到

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
投票

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

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

        }

休息也一样。

© www.soinside.com 2019 - 2024. All rights reserved.