I’m writing functionality to upload an image along with some metadata to a service that is expecting a POST operation with the image encoded in base64. However, the image data seems to get mangled when it is posted to the server, and doesn’t produce a valid image. I opted to use the URLRequest framework rather than HTTPService because the service returns an inline download that the user will want to save.
Is there somewhere in this URLRequest call where I’m handling the encoding incorrectly?
public function imageExportHandler():void
{
trace(this);
var request:URLRequest = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = imageExportServiceUrl;
var params:Object = {
image: encodeImageBase64(imageData),
name: StringUtil.substitute("map-{xmin},{ymin}-{xmax},ymax}", imageExtent),
format: Model.instance.imageExportModel.selectedFormat
};
request.data = new URLVariables(StringUtil.substitute("image={image}&format={format}&name={name}", params));
navigateToURL(request, "_blank");
}
private function encodeImageBase64(toEncode:BitmapData):String
{
var pngEncoder:PNGEncoder = new PNGEncoder();
var data:ByteArray = pngEncoder.encode(toEncode);
var base64Encoder:Base64Encoder = new Base64Encoder();
base64Encoder.encodeBytes(data);
return base64Encoder.flush();
}
It turns out that base64Encoder.flush() wasn’t properly terminating the encoded string – the correct function to use is base64Encoder.toString().