我正在尝试使用alamofire 4.7.1使用此代码上传图像,但说实话我怀疑我没有编写正确的代码来上传图像
func uploadDefect(defectRemark: String, defectLocation: String, defectImage: UIImage, fileNameImage: String, completion: @escaping(_ errorMessage: String?) -> Void) {
guard let imgData = defectImage.jpeg(.medium) else {return}
let urlUpload = URLService.uploadDefect.endPoint
let username = "admin"
let password = "1234"
let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": base64Credentials]
let parameters : [String:Any] = ["defect_remark" : defectRemark, "defect_location": defectLocation, "tenant_id" : tenantID]
let url = try! URLRequest(url: URL(string: urlUpload)!, method: .post, headers: headers)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "file", fileName: fileNameImage, mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
with: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("upload response: \(response)")
switch response.result {
case .failure(let error) :
let message : String
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 404:
message = "File not found"
case 500 :
message = "Internal Error"
default:
message = "Connection issue, please make sure you have a good internet access, or please contact IT Support."
}
} else {
message = error.localizedDescription
}
completion(message)
case .success( _) :
completion(nil)
}
}
case .failure(let encodingError):
let messageEncodingError = encodingError.localizedDescription
print(encodingError)
completion(messageEncodingError)
break
}
}
)
}
似乎是案件.success被触发
case .success( _) :
completion(nil)
}
但似乎没有错误,但我没有从服务器获得预期的JSON响应。
这是来自调试区域的错误日志
我怀疑我没有使用alamofire使用基本身份验证编写正确的代码来上传图像服务器。你能帮帮我吗?
答案 0 :(得分:4)
像这样更改Authorization
:
let headers = ["Authorization": "Basic \(base64Credentials)"]
您还可以使用Alamofire
创建身份验证标头,如:
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}