我正在使用Alamofire Multipart将pdf文件上传到服务器,并且如果我发送pdf.datarepresentation,它会成功上传,但是如果我使用zlib压缩此数据,则会从服务器获取以下错误-
上传失败。400错误的请求:浏览器(或代理)发送了该服务器无法理解的请求。
上传pdf代码
func uploadJsonForPdfs(params:[String:String],pdfData:Data?,fileName:String) {
Alamofire.upload(multipartFormData: { (MultipartFormData) in
for (key,value) in params {
MultipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = pdfData {
MultipartFormData.append(data, withName: "file",fileName: fileName, mimeType: "application/pdf")
}
}, usingThreshold: UInt64.init(), to: baseUrl, method: .post) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded = \(response) " )
if let err = response.error{
print(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
当 pdfData = pdf.dataRepresentation()时工作正常,但当 pdfData = pdf.dataRepresentation()。deflated
时失败已删除来自此处
extension Data {
func compression(isEncode: Bool, algorithm: compression_algorithm) -> Data? {
return withUnsafeBytes { (urbp: UnsafeRawBufferPointer) in
let ubp: UnsafeBufferPointer<UInt8> = urbp.bindMemory(to: UInt8.self)
let up: UnsafePointer<UInt8> = ubp.baseAddress!
let destCapacity = 1_000_000 // Note: Increase/decrease as you require.
let destBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity:
destCapacity)
defer { destBuffer.deallocate() }
let destBytes = isEncode ?
compression_encode_buffer(destBuffer, destCapacity, up, count, nil,
algorithm) :
compression_decode_buffer(destBuffer, destCapacity, up, count, nil,
algorithm)
guard destBytes != 0 else { return nil } // Error, or not enough size.
return Data(bytes: destBuffer, count: destBytes)
}
}
var deflated: Data? {
// ZLIB has no headers, so it is effectively DEFLATE.
return compression(isEncode: true, algorithm: COMPRESSION_ZLIB)
}
var inflated: Data? {
return compression(isEncode: false, algorithm: COMPRESSION_ZLIB)
}
}