Ios 使用多部分和承载令牌上传图像
我尝试在服务器上上传图像。它在邮递员那里工作。但从我的代码来看,它的显示总是验证失败Ios 使用多部分和承载令牌上传图像,ios,swift,file-upload,alamofire,multipart,Ios,Swift,File Upload,Alamofire,Multipart,我尝试在服务器上上传图像。它在邮递员那里工作。但从我的代码来看,它的显示总是验证失败 func uploadPhoto( image: UIImage, completion: @escaping (JSON) -> ()) { let url = "\(AppConstant.imageUpload)" // let headers: HTTPHeaders // headers = [ // "Authoriza
func uploadPhoto( image: UIImage, completion: @escaping (JSON) -> ()) {
let url = "\(AppConstant.imageUpload)"
// let headers: HTTPHeaders
// headers = [
// "Authorization": "Bearer \(AppConstant.token))"
// ]
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data",
"Authorization": "Bearer \(AppConstant.token))"
]
// let headers: HTTPHeaders = [
// "Content-type": "multipart/form-data",
// "Content-Disposition" : "form-data",
// "Authorization": "Bearer \(AppConstant.token))"
// ]
//
//
// let headers: HTTPHeaders = [
// "Content-Type": "application/json",
// "Content-Disposition" : "form-data",
// "Authorization": "Bearer \(AppConstant.token))"
// ]
// let headers: HTTPHeaders = [
// "Content-type": "application/form-data",
// "Authorization": "Bearer \(AppConstant.token))"
// ]
// let headers: HTTPHeaders = [
// "Content-Type": "application/json",
// "Authorization": "Bearer \(AppConstant.token))"
// ]
//
print("token \(AppConstant.token) url: \(url)")
// let httpHeaders = HTTPHeaders(headers)
AF.upload(multipartFormData: { multiPart in
multiPart.append(image.jpegData(compressionQuality: 0.4)!, withName: "image", fileName: "file.jpg", mimeType: "image/jpg")
}, to: url, method: .post, headers: headers) .uploadProgress(queue: .main, closure: { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}).responseString(completionHandler: { data in
print("upload finished: \(data.data)")
}).response { (response) in
print("upload responce: \(response.data)")
switch response.result {
case .success(let resut):
DispatchQueue.main.async {
do{
// self.imageUrl = try JSONDecoder().decode(ImageUploadUrl.self, from: resut!)
if let data = resut,
let urlContent = NSString(data: data, encoding: String.Encoding.ascii.rawValue) {
print("urlContent \(urlContent)")
} else {
print("Error: ")
}
print("upload 10 \(self.imageUrl?.url)")
}catch {
print("error occur ")
}
}
print("upload success result: \(resut)")
case .failure(let err):
print("upload err: \(err)")
}
}
}
我发现您在标题中键入错误: 您编写的标题如下所示:
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data",
"Authorization": "Bearer \(AppConstant.token))"
]
但是您必须删除标记最后的括号,所以您的代码应该是这样的
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data",
"Authorization": "Bearer \(AppConstant.token)"
]
希望对您有所帮助您正在使用AFN网络吗?那么您使用的是哪一版本的AFNetworking?谢谢您的帮助。。。最近5小时搜索我的错误,但未找到。