使用 Alamofire(多部分数据)上传带有额外参数的 .PDF 文件时出错
Posted
技术标签:
【中文标题】使用 Alamofire(多部分数据)上传带有额外参数的 .PDF 文件时出错【英文标题】:error uploading .PDF files with extra parameters using Alamofire (Multi Part Data) 【发布时间】:2020-03-03 13:17:53 【问题描述】:我正在尝试使用 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))
【问题讨论】:
【参考方案1】:这个错误是因为服务器配置发生了一些变化,所以任何人都想使用 alamofire 将文件或图像上传到服务器,这种方法效果很好
【讨论】:
以上是关于使用 Alamofire(多部分数据)上传带有额外参数的 .PDF 文件时出错的主要内容,如果未能解决你的问题,请参考以下文章