Following function gives an example of how to doanload a file in Flex.
"file" object passed to the function is a simple object having following structure:
"file" object passed to the function is a simple object having following structure:
file.fileName = "Abc.png" file.fileType = "image/png" file.url = "/documents/Abc.png"A pattern match-replacement is used to determine file extension, in case fileName does not have it.
public function downloadFile(file:Object):void
{
if (file != null)
{
var fileName:String = (file.fileName != null && file.fileName.length > 0) ? file.fileName : (new Date()).time.toString();
var fileExtension:String = file.fileExtension;
if (fileName.indexOf(".") < 0)
{
if (fileExtension.lastIndexOf(".") >= 0)
fileExtension = fileExtension.slice(fileExtension.lastIndexOf("."), fileExtension.length);
else if (fileExtension.lastIndexOf("/") >= 0)
fileExtension = "." + fileExtension.slice(fileExtension.lastIndexOf("/"), fileExtension.length);
else
fileExtension = "." + fileExtension;
// Replace characters not supported by download. / \ : * ? " < > | % with _
var pattern:RegExp = /([\/\\:\*\?\"\<\>\|\%])/g;
fileName += fileExtension.replace(pattern, "_");
}
var urlRequest:URLRequest = new URLRequest(file.url);
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(IOErrorEvent.IO_ERROR, fileDownloadError);
fileRef.download(urlRequest, fileName);
}
function fileDownloadError(event:IOErrorEvent):void
{
Alert.show("Error encountered while downloding the file:\n." + event.text, "Error");
}
}
Comments