【问题标题】:Alamofire 4 and Swift 3 Image upload with other parametersAlamofire 4 和 Swift 3 使用其他参数上传图片
【发布时间】:2017-04-22 15:39:58
【问题描述】:

我正在尝试上传带有其他参数的图像,当我的一个参数的数据类型为 [String] 时会出现问题。服务器端的数组将为空。:/ 使用其他数据类型一切正常。

  self.manager.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: imgKey, fileName: "image.jpg", mimeType: "image/jpg")

                for (key, value) in params {
                    multipartFormData.append(serialize(value)!, withName: key)
                }

            },
            to: path,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint("SUCCESS RESPONSE: \(response)")
                    }
                case .failure(let encodingError):
                    print("ERROR RESPONSE: \(encodingError)")

                }
            }
        )

func serialize(_ value: Any) -> Data? {
        if JSONSerialization.isValidJSONObject(value) {
            return try? JSONSerialization.data(withJSONObject: value, options: [])
        }
        else {
            return String(describing: value).data(using: .utf8)
        }
    }

我的参数是[String: Any]

我到底做错了什么? :(

问题肯定出在客户端。当我使用 Postman 或其他 HTTP 服务时,一切正常

【问题讨论】:

  • 分享你的邮递员截图,让我看看

标签: ios swift alamofire


【解决方案1】:
Alamofire.upload(multipartFormData: { multipartFormData in
    var index = 1
    for image in imageArray {
        let imageData: Data = (UIImageJPEGRepresentation(image, 1.0) as Data?)!

        multipartFormData.append(imageData, withName: "home-\(index)", fileName: "home-\(index)", mimeType: "image/jpeg")

        index += 1
    }
    }, with: requestName, encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print("Image(s) Uploaded successfully:\(response)")
            }
        case .failure(let encodingError):
            print("encodingError:\(encodingError)")
        }
})

【讨论】:

    【解决方案2】:

    我知道问题指南说不要要求澄清,但我还没有足够的代表发表评论。

    您如何访问服务器上的阵列?您是如何将数组与其他服务一起发送的?

    更重要的是,看起来params[String:String]。您如何为其添加 [String] 值?你在序列化它吗?

    【讨论】:

    • 我的参数是 [String: Any] 是的,我在下面显示它并更新我的答案我如何序列化它。
    • @BilalReffas 它仍然不能使用更新的序列化方法?只是从阅读我看来不错的文档。我会使用一些断点/日志记录来确保 JSONSerialization.isValidJSONObject 方法为数组返回 true。
    • @BilalReffas 好的,请确认一下,您是如何访问服务器上的阵列的?您是否期待 JSON 字符串并对其进行解析?如果是这样,我会尝试使用 [String:String] 的参数并将数组转换为 Luis 刚刚建议的字符串
    【解决方案3】:

    我使用此代码上传所需的尽可能多的图像和参数,希望对您有所帮助

    Alamofire.upload(multipartFormData: { (MultipartFormData) in
                var secondCounter = 0
                for data in imageDataArray {
                    print(imageNamesArray[secondCounter])
                    MultipartFormData.append(data, withName: imageNamesArray[secondCounter], fileName: imageNamesArray[secondCounter] + "myImage.png", mimeType: "application/octed-stream")
                    secondCounter = secondCounter + 1
                }
                contentDict = parameters as! [String : String]
                for (key, value) in contentDict {
                    MultipartFormData.append(value.data(using: .utf8)!, withName: key)
                }
                }, to: url, method: .post, headers: nil, encodingCompletion: { (result) in
                    switch result {
                    case .success(let upload, _, _):
                        upload.responseJSON(completionHandler: { (dataResponse) in
                            if dataResponse.result.error != nil {
                                completion(nil, nil, dataResponse.result.error as? NSError, false)
                            }
                            else {
                                print(dataResponse.result.value)
                                completion(nil, nil, nil, true)
                            }
                        })
                    case .failure(let encodingError):
                        print(encodingError)
                        completion(nil, nil, nil, false)
                    }
    

    忽略打印,哈哈

    【讨论】:

    • 你的参数也包含数组吗?
    • 是的,在那个应用中我上传了 12 张图片和 4 个数组
    • 你的参数怎么可能是数据类型 [String: String]
    • 我将数组转换为Json字符串,在调用函数之前我会这样做对不起,就像这样let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil) let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
    【解决方案4】:

    它对我有用。解决方案非常简单,因为您使用 MultipartFormData 上传需要查看的文件到RFC 2388。要上传数组,您需要这种非常重要的格式。 例如,如果你想上传一个字符串数组,你需要在你的键中包含括号!!!

    Value: "234234"  Key: keyname[]
    

    您需要一次又一次地将数据追加到循环中。

    例如看看这个使用 Alamofire 的 swift 代码。

    for (key, value) in params {
                if JSONSerialization.isValidJSONObject(value) {
                    let array = value as! [String]
    
                    for string in array {
                        if let stringData = string.data(using: .utf8) {
                            multipartFormData.append(stringData, withName: key+"[]")
                        }
                    }
    
                } else {
                    multipartFormData.append(String(describing: value).data(using: .utf8)!, withName: key)
                }
            }
    

    如果变量是有效的 JSONObject,我会将数据附加到我的数组中。同样不要忘记在您的关键字中包含 [] 括号。

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 2017-07-14
      • 2018-07-31
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 2017-06-10
      • 2018-08-10
      相关资源
      最近更新 更多