如何使用Alamofire上传图像并参考params中的文件

时间:2017-10-15 06:42:07

标签: swift http alamofire postman

我可以将图像发送到API(用于审核)并将其链接到邮递员中的“媒体”参数,如下所示:

enter image description here

现在我正试图在swift中做同样的事情。我按照示例here但出现错误:未指定媒体。继承我的代码:附加的图像文件是否未正确链接到媒体参数?

    let image = self.descriptionImage.image!
    let parameters = [
        "api_user": "xxxxx",
        "api_secret": "xxxxx",
        "models": "nudity,wad",
        "media": "file.png"
    ]

    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image, 1) {
            multipartFormData.append(imageData, withName: "file.png", fileName: "file.png", mimeType: "image/png")
        }

        for p in parameters {
            let value = p.value
            multipartFormData.append((value.data(using: .utf8))!, withName: p.key)
        }}, to: "https://api.sightengine.com/1.0/check.json", method: .post, headers: nil,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.response { [weak self] response in
                        guard let strongSelf = self else {
                            return
                        }
                        print(response.data)
                        print("strongSelf")

                        debugPrint(response)

                    }
                case .failure(let encodingError):
                    print("error:\(encodingError)")
                }
    })

1 个答案:

答案 0 :(得分:2)

应在多部分表单数据中指定图像的参数,尝试将代码更改为:

let image = self.descriptionImage.image!
let parameters = [
    "api_user": "xxxxx",
    "api_secret": "xxxxx",
    "models": "nudity,wad"
]

Alamofire.upload(multipartFormData: { multipartFormData in
    if let imageData = UIImagePNGRepresentation(image) {
        multipartFormData.append(imageData, withName: "media", fileName: "file.png", mimeType: "image/png")
    }

    for p in parameters {
        let value = p.value
        multipartFormData.append((value.data(using: .utf8))!, withName: p.key)
    }}, to: "https://api.sightengine.com/1.0/check.json", method: .post, headers: nil,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.response { [weak self] response in
                    guard let strongSelf = self else {
                        return
                    }
                    print(response.data)
                    print("strongSelf")

                    debugPrint(response)

                }
            case .failure(let encodingError):
                print("error:\(encodingError)")
            }
})