我正在尝试使用Alamofire从ios应用程序上传PDF,但是我一直收到响应错误:
成功:{
status = 400;
title = "Bad Request";
traceId = "0HLTUPOJDQ33R:00000001";
type = "https://tools.ietf.org/html/rfc7231#section-6.5.1";
}
尽管请求在邮递员中使用相同的参数进行工作,并且我正在使用此方法在其他应用程序中上传文件,但效果很好,我试图在我的代码中找出问题,因为几天以来,我做不到,这是我的代码
static func uploadMultiPartData<T:Decodable>(endUrl: String, fileURL: URL, parameters: [String : Any]?, completion: ((_ result: Result<T>) -> Void)?) {
let token = Helper.getUserDetails()["token"] as! String
let auth = "Bearer \(token)"
let headers: HTTPHeaders = [
"Authorization" : auth,
"Content-type": "multipart/form-data"
]
var image:UIImage?
var dataToBeSend:Data?
Alamofire.upload(multipartFormData: { (multipartFormData) in
if let parms=parameters{
for (key, value) in parms {
multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key as String)
}
}
guard let fileData = try? Data(contentsOf: fileURL as URL) else {
print("There was an error!")
// return or break
return
}
let filename : String = fileURL.lastPathComponent
let splitName:[String] = filename.components(separatedBy: ".")
let name = splitName.first
let filetype = splitName.last
if filetype?.uppercased() != "PDF"{
image=UIImage(data: fileData)
dataToBeSend = image!.jpegData(compressionQuality: 0.2)!
}else{
dataToBeSend=fileData
}
if let data = dataToBeSend{
multipartFormData.append(data, withName: "\(name ?? "name")", fileName: "\(filename)", mimeType: "\(name ?? "name")/\(filetype ?? "jpg")")
}
}, usingThreshold:0, to: endUrl, method: .post, headers: headers) { (result) in
print(result)
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
if let err = response.error{
completion?(.failure(err))
return
}
if let value = (try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments)) as? T {
completion?(.success(value))
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
completion?(.failure(error))
}
}
}
答案 0 :(得分:0)
此错误是因为服务器配置发生了一些变化,所以任何人都想使用alamofire将文件或图像上传到服务器,这种方法效果很好