首页 > 解决方案 > 图片未上传,而 API 调用(通过 PATCH 方法)成功,Alamofire,Swift

问题描述

我想使用在补丁方法上运行的 API 将图像上传到服务器,API 还需要一个身份验证令牌。

Alamofire.upload(
                multipartFormData: { MultipartFormData in

                    for (key, value) in params {
                        if let image = value as? UIImage {
                            if let imageData = UIImageJPEGRepresentation(image, 0.7) {
                                MultipartFormData.append(imageData, withName: "image", fileName: "file\(arc4random()).jpg", mimeType: "image/jpeg")
                            }
                        }else {
                            MultipartFormData.append(String(describing: value).data(using: String.Encoding.utf8)!, withName: key)
                        }
                    }

            }, to:url, method: .patch, headers: ["content-type":"application/json","token": authToken]) { (result) in

                switch result {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        guard response.result.isSuccess else {
                            print(response.error?.localizedDescription ?? "Error while requesting")
                            completionHandler(nil)
                            return
                        }
                        if let value = response.result.value {
                            let json = JSON(value)
                            print(json)
                        }else {
                            completionHandler(nil)
                        }
                    }

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

问题是API调用成功但图片没有上传到服务器上,请帮帮我。

谢谢

标签: swiftalamofireimage-uploadingmultipartform-data

解决方案


推荐阅读