Jennifer Heidelberg
Jennifer Heidelberg

Reputation: 41

AS3 Function to start download after clicking a button!

I need an actionscript 3 function for my website, that lets people download a document after they have clicked on a button.

Couldn't find this anywhere on the net.

Thanks! Jennifer

Upvotes: 4

Views: 7264

Answers (2)

Amarghosh
Amarghosh

Reputation: 59461

FileReference::download()

btn.addEventListener(MouseEvent.CLICK, promptDownload);

private function promptDownload(e:MouseEvent):void
{
  req = new URLRequest("http://example.com/remotefile.doc");
  file = new FileReference();
  file.addEventListener(Event.COMPLETE, completeHandler);
  file.addEventListener(Event.CANCEL, cancelHandler);
  file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
  file.download(req, "DefaultFileName.doc");
}

private function cancelHandler(event:Event):void 
{
  trace("user canceled the download");
}

private function completeHandler(event:Event):void 
{
  trace("download complete");
}

private function ioErrorHandler(event:IOErrorEvent):void 
{
  trace("ioError occurred");
}

Upvotes: 5

Daniel Carvalho
Daniel Carvalho

Reputation: 557

If you make a button, and give it an instance name of iBtn_Download, the code to make it work will be as follows. Just paste the following code into the timeline of your project. Just change the template website address to where your document sits.

iBtn_Download.addEventListener(MouseEvent.CLICK, downloadDocument);

function downloadDocument(_event:MouseEvent):void
{
    var urlRequest:URLRequest = new URLRequest("http://www.yourwebsite.com/downloads/document.pdf");

    navigateToURL(urlRequest);
}

Upvotes: 0

Related Questions