如何在Swift中使用Alamofire在多部分文件上传中传递body参数和文件

时间:2015-10-15 13:59:54

标签: ios swift ios9 alamofire

我正在使用Swift中的Alamofire Library处理多部分文件上传。我需要传递一些参数和文件。以下是我需要传递给服务器的主体:

{
  "eventId":7,
  "eventImageList":[
    { "contentType":"png", "imageName":"test", "imagePath":"" }
    ,
    { "contentType":"png", "imageName":"test2", "imagePath":"" }
  ]
}

我尝试过类似的事情:

let image = UIImage(named: "sampleImage")

Alamofire.upload(.POST, URL, multipartFormData: {
    multipartFormData in
        if let _image = image {
            if let imageData = UIImageJPEGRepresentation(_image, 0.5) {
                multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
            }
        }
        for (key, value) in dictionary {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key as! String)
        }

    }, encodingCompletion: {
        encodingResult in

        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in

                switch response.result {
                case .Success:
                     print("jsonResponse ==== ", response)
                case .Failure(let error):
                     print("error ==== ", error)
                }
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
})

我需要传递这个数组:

[
  { "contentType":"png", "imageName":"test", "imagePath":"" }
  ,
  { "contentType":"png", "imageName":"test2", "imagePath":"" }
]  

但是当我像下面那样解码它时,应用程序会崩溃。

multipartFormData.appendBodyPart(data:value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)

2 个答案:

答案 0 :(得分:1)

当我尝试使用类似参数(字典中的字典)上传图像(Alamofire)时,我遇到了这个问题。

以下是一个例子:

let params:[String:Any] = ["client" : ["name" : "Some", "email" : "some@some.com"]]
for (key, value) in (params["client"] as! [String:Any]) {
     multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: "client[\(key)]")
 }

诀窍在于这部分:

withName: "client[\(key)]"

答案 1 :(得分:0)

更改您的代码
for (key, value) in dictionary {
    multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key as! String)
}

到此:

for (key, value) in parameters {
    multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}

这适合我。