Alamofire 4和Swift 3的图像上传以及其他参数 [英] Alamofire 4 and Swift 3 Image upload with other parameters

查看:80
本文介绍了Alamofire 4和Swift 3的图像上传以及其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to upload a image with other parameters the issue occurs when my one of my parameters have a datatype of [String]. The array will be empty on the server side.:/ With other datatypes everything works well.

  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]

我到底在做什么错? :(

What I'm exactly doing wrong? :(

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

The problem it's definitely on the client side. Everything works fine when I'm using Postman or other HTTP Services

推荐答案

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

这篇关于Alamofire 4和Swift 3的图像上传以及其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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