我尝试在服务器中上传图像。它正在邮递员工作。但是从我的代码来看,它的显示总是认证失败。
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)"
]
希望帮助