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');
3
  • Does this answer your question? Javascript - Download CSV as File Commented Jul 3, 2020 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. Commented Jul 3, 2020 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. Commented Jul 3, 2020 at 13:39

2 Answers 2

1

Use

aLink.click();

instead of the Dispatch-event

Sign up to request clarification or add additional context in comments.

2 Comments

see this link 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.
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 ?
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.