我有一个使用Alamofire来处理所有请求的工作项目,包括使用多部分数据上传。目前此工作正常,但我们希望将GZIP用于所有请求和响应。我正在使用gzip swift库,现在可以通过请求接收gzip压缩数据,但我无法弄清楚如何gzip编码导致调用失败的多部分数据。
我已经搜索了一个解决方案,虽然我遇到过一篇关于它的文章,但提供的示例是针对较旧的Alamofire和Swift构建的。我试图破解它以使其工作,但有一些我无法解决的错误。
我的请求代码如下:
self.sessionManager.upload(
multipartFormData: { multipartFormData in
multipartFormData.append("\(sUUID)".data(using: String.Encoding.utf8)!, withName: "sUUID")
multipartFormData.append(sStream, withName: "files[]", fileName: fileName, mimeType: "image/\(sExt)")
multipartFormData.append("\(convertedEventID)".data(using: String.Encoding.utf8)!, withName: "nEventID")
multipartFormData.append("\(sExt)".data(using: String.Encoding.utf8)!, withName: "sExt")
multipartFormData.append("0".data(using: String.Encoding.utf8)!, withName: "bRecurring")
multipartFormData.append("\(fileName)".data(using: String.Encoding.utf8)!, withName: "sDescription")
multipartFormData.append("File Attached By User".data(using: String.Encoding.utf8)!, withName: "sWordDocumentType")
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "sWordDocumentName")
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "sSname")
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "sEmailRecip")
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "sEmailSender")
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "sNotes")
multipartFormData.append("ME".data(using: String.Encoding.utf8)!, withName: "sAgent")
},
to: "/Upload",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
let decompressedData: Data
if response.data!.isGzipped {
decompressedData = try! response.data!.gunzipped()
} else {
decompressedData = response.data!
}
NotificationCenter.default.post(name: .didReceiveData, object: self, userInfo: ["pass" : 1])
completion(true, 200, decompressedData, nil)
}
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
case .failure(let encodingError):
print(encodingError)
completion(false, 404, nil, encodingError)
}
})
如果你需要像gzip编码那样进行后期处理,你将无法使用内置的upload(multipartFormData:...)
方法。相反,您需要单独使用Alamofire的多部分编码,生成数据,gzip,然后使用Alamofire上传。
此外,您无需手动解压缩响应。只要适当的Content-Encoding
标题返回表明它已被gzip压缩,它应该自动解压缩。
最后,您可以使用Data
更轻松地从String
s创建Data("string".utf8)
值。