Lightning Controller
getData : function(component, file, fileContents) { var action = component.get("c.data"); action.setCallback(this, function(response) { var state = response.getState(); var csvContent = response.getReturnValue(); if (component.isValid() && state === "SUCCESS") { var encodedUri = encodeURI(csvContent); //Security review states that the below code violates DOM Modification rule var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "data.csv"); document.body.appendChild(link); link.click(); } }); $A.enqueueAction(action); },
other try was using window.open(encodedUri)
is there any possibility to download .csv
in Lightning Component without manipulating DOM?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Modern browsers support Data URIs, meaning that you can do this:
app
<aura:application > <ui:button label="Download" press="{!c.download}" /> </aura:application>
controller
({ download: function(component, event, helper) { var a = document.createElement("a"); a.href = "data:text/csv,base64;ImhlbGxvIiwid29ybGQiCg=="; a.download = "text.csv"; a.click(); } })
The file will download automatically or provide a prompt for the user, depending on the browser. It is not necessary to add the link to the DOM for this to work.
In practice, you’ll want to base64 encode your return value in Apex, so you can append it directly:
getData : function(component, file, fileContents) { var action = component.get("c.data"); action.setCallback(this, function(response) { var state = response.getState(); var csvContent = response.getReturnValue(); if (component.isValid() && state === "SUCCESS") { var link = document.createElement("a"); link.href = "data:text/csv;base64,"+csvContent; link.download = "data.csv"; link.click(); } }); $A.enqueueAction(action); },
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0