2

I'm trying to download a PDF file and I wish to give a name to this file and a extension.

Here is what I did:

Component:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global"> <lightning:button variant="base" label="Download PDF" title="Download PDF" onclick="{! c.getPDF }"/> </aura:component>

JS Controller:

({
getPDF : function(component, event, helper) {
    helper.parseBase64toFile();
}
})

JS Helper:

({
parseBase64toFile : function() {
    var base64 = 'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
      'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
      'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
      'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
      'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
      'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
      'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
      'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
      'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
      'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
      'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
      'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
      'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G'
    var url = 'data:application/octet-stream;base64,' + base64;
    var urlEvent = $A.get('e.force:navigateToURL');

    console.log('url');
    console.log(url);
    urlEvent.setParams({
        "url": url
    });
    urlEvent.fire();
}
})

the name is 'download' as default and there is no extension

1 Answer 1

4

If you change the way your component works rather than using a force:navigateToURL event and instead put your octet stream into an anchor tag, you can use the download attribute on the <a> tag to specify a filename and extension.

<a download="myfile.pdf" href="data:application/octet-stream;base64,...">Download PDF</a>

Unfortunately the data URL scheme does not have a mechanism built in for specifying the file name and extension. Also refer to this Stackoverflow post.

The other possible approach is setting the HTTP headers for your URL.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .