Alamofire 4上传参数

时间:2016-10-01 18:05:08

标签: swift3 alamofire

我正在执行以下操作以上传包含参数的PNG文件:

    Alamofire.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(UIImagePNGRepresentation(tempImage!)!, withName: "file", fileName: "picture.png", mimeType: "image/png")

            // Send parameters
            multipartFormData.append((UserDefaults.standard.value(forKey: Email) as! String).data(using: .utf8)!, withName: "email")
            multipartFormData.append("png".data(using: .utf8)!, withName: "type")

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

            }
        }
    )

问题是我的服务器上没有emailtype表单字段。我按照在线发布的示例进行了操作。有什么我应该做的不同吗?

修改

如果我删除我放置的部分:

multipartFormData.append(UIImagePNGRepresentation(tempImage!)!, withName: "file", fileName: "picture.png", mimeType: "image/png")

然后包含参数。否则,我认为这是Alamofire 4.0.1中的一个错误。

2 个答案:

答案 0 :(得分:40)

它的工作正常。

我正在使用以下代码:

let parameters = [
            "file_name": "swift_file.jpeg"
        ]

Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 1)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
            }, to:"http://sample.com/upload_img.php")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
            })

            upload.responseJSON { response in
                //print response.result
            }

        case .failure(let encodingError):
               //print encodingError.description
        }
    }

答案 1 :(得分:2)

如果您的值为Any类型,则可以像这样更改

for (key, value) in params {
    let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
    formData.append(paramsData, withName: key)
}