使用其他参数上传Alamofire 4和Swift 3图片

时间:2016-12-07 15:52:56

标签: ios swift alamofire

当我的一个参数的数据类型为[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服务

时,一切正常

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

您如何访问服务器上的阵列?你是如何使用其他服务发送数组的?

更重要的是,params似乎是[String:String]。您如何为此添加[String]值?你在序列化吗?

答案 2 :(得分:0)

我使用此代码上传我想要的任意数量的图像和参数,我希望它有所帮助

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

忽略打印Lol

答案 3 :(得分:0)

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

Value: "234234"  Key: keyname[]

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

例如,使用Alamofire查看这个快速代码。

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,我将数据附加到我的数组。再次,不要忘记在关键字中添加[]括号。