I need to perform a multipart-data request to upload an image on an API.
What I want to do it's to predict the length of the HTTPBody, because I need this value in my header, for the authentication. Is there a way after building the request to know the total length ?
In the encodingCompletion I get my Request called upload, but the upload.request is nil.
So I can't check for example the length like : upload.request.HTTPBody.lenght.
Alamofire.upload(method, path, headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: data, name: "picture")
if let parameters = parameters {
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :key)
}
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
self.request = upload
self.handleJSONResponse(upload, blockSuccess: blockSuccess, blockError: blockError)
case .Failure(let encodingError):
print(encodingError)
blockError(.None)
}
})
Maybe there is an issue in the server side to determine the length body, but impossible to get the same value in the client (馃摫), not even close.
Thanks in advance 馃惃馃憤
Hi @remirobert,
In this case, you'll want to drop down a level in the APIs and first construct the multipartFormData. Once you have it encoded, you can then figure out the length of the data, and use that for your header. After gathering all the data, then you can build the request using the upload API without multipartFormData.
func uploadMultipartFormData() {
let multipartFormData = MultipartFormData()
multipartFormData.appendBodyPart(data: imageData, name: "picture")
var encodedData: NSData?
do {
encodedData = try multipartFormData.encode()
} catch {
print(error)
}
guard let data = encodedData else { return }
Alamofire.upload(.POST, URLString, headers: ["ContentSize": data.length], data: data)
}
Just FYI...I didn't test any of that code. It's purely to demonstrate how you could solve this problem. Hopefully that helps.
Cheers. 馃嵒
Most helpful comment
Hi @remirobert,
In this case, you'll want to drop down a level in the APIs and first construct the multipartFormData. Once you have it encoded, you can then figure out the length of the data, and use that for your header. After gathering all the data, then you can build the request using the
uploadAPI without multipartFormData.Just FYI...I didn't test any of that code. It's purely to demonstrate how you could solve this problem. Hopefully that helps.
Cheers. 馃嵒