App开发中使用Alamofire 5上传图片文件
最近开发中要上传图片到通过wordpress rest api,使用Alamofire5很方便
restapi地址 http://../wp-json/wp/v2/media/
Xcode的方法:
public func uploadDocument(file: Data,filename : String,handler : @escaping (String) -> Void) {
let bearertoken:String = "Bearer "+tokenadmin
let headers :HTTPHeaders = [
"Authorization": bearertoken,
"Content-type": "multipart/form-data",
"Content-Disposition": "form-data;filename=Task.jpg",
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(file, withName: "file" , fileName: filename, mimeType: "image/jpeg")
},
to: Global.REQUEUPLOADMEDIA, method: .post , headers: headers)
.response { response in
switch response.result{
case .failure(let error):
print(error)
case .success(_):
let json = response.data
if (json != nil)
{
do{
if let jsonData = response.data{
let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary
print(parsedData)
}
}catch{
print("error message")
}
}
}
}
}
调用
guard let imagetask = UIImage(named: "Task.jpg")?.jpegData(compressionQuality: 0.5) else {return}
WPApi.shared.uploadDocument(file: imagetask, filename: "Task.jpg") { (res) in
}
如显示错误
“code”: rest_upload_unknown_error, “message”: Specified file failed upload test., “data”: {
status = 500;
}]
请检查
multipartFormData.append(file, withName: “file” , fileName: filename, mimeType: “image/jpeg”)
withname 须为file