0

I have a url which has csv file. i want to download that file by JavaScript. during download i will provide file name and by that name file will be download in client pc. i tried below code which is not working. where i made the mistake. please give me hint.

function downloadFile(fileName, urlData) {

    var aLink = document.createElement('a');
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click");
    aLink.download = fileName;
    aLink.href = urlData;
    aLink.dispatchEvent(evt);
}

downloadFile('Test.csv', 'https://testsite.com/targeting/Export/aa.csv');
Indi_Rain
  • 179
  • 5
  • 17
  • Does this answer your question? [Javascript - Download CSV as File](https://stackoverflow.com/questions/21177078/javascript-download-csv-as-file) – xMayank Jul 03 '20 at 13:36
  • @xMayank see i have given the answer for my own post. which is woking but i have one small problem that i need to give a different name when file will download in user pc. how to change in my code for that. can you guide me. – Indi_Rain Jul 03 '20 at 13:38
  • @xMayank in my url file name is aa.csv but i want it should be download in client pc as holding.csv as a file name. what to change in my code ? please share idea. – Indi_Rain Jul 03 '20 at 13:39

2 Answers2

1

Use

aLink.click();

instead of the Dispatch-event

  • see this link https://stackoverflow.com/a/62716581/13722367 it is working but when i am giving different name for file which is not working. i want file should be downloading in client pc with different name....what to change in my code. see the link in this post. – Indi_Rain Jul 03 '20 at 13:44
  • thanks after i add .click() now file is downloading but i want to change downloading file name in client pc which will downloading by above code. now csv file name is aa.csv but it should be download in client pc as holding.csv...how it is possible ? – Indi_Rain Jul 03 '20 at 13:49
0

I found code which worked. here is the code which i am following now.

    var url = 'https://testsite.com/targeting/Export/aa.csv';
    var a = document.createElement("a");
    a.href = url;
    fileName = url.split("/").pop();
    alert(fileName);
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
Indi_Rain
  • 179
  • 5
  • 17