使用Alamofire Swift将图像上传到服务器

时间:2020-10-27 13:20:21

标签: swift alamofire urlsession

我正在尝试将图像上传到服务器,但是显示的不是当前格式,我在堆栈中看到了很多解决方案,但是对我的代码不起作用。

这是我的邮递员:postman response 的auth屏幕截图: Screenshot of Authorization page

我尝试使用Alamofire的

代码:`

func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {
        AF.upload(multipartFormData: { multiPart in
            for (key, value) in params {
                if let temp = value as? String {
                    multiPart.append(temp.data(using: .utf8)!, withName: key)
                }
                if let temp = value as? Int {
                    multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
                }
                if let temp = value as? NSArray {
                    temp.forEach({ element in
                        let keyObj = key + "[]"
                        if let string = element as? String {
                            multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                        } else
                            if let num = element as? Int {
                                let value = "\(num)"
                                multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                        }
                    })
                }
            }
            multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")
        }, with: url)
            .uploadProgress(queue: .main, closure: { progress in
                //Current upload progress of file
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            .responseJSON(completionHandler: { data in
                //Do what ever you want to do with response
            })
    }

`

现在我需要使用url session或Alamofire上传图像的帮助。 还需要有关网址参数的帮助:

网址为:“ http://germanbutcher.easyservice.xyz/backend/api/v1/users/33/photo” 预先感谢

0 个答案:

没有答案