How to download a file in JavaScript or jQuery

14,611

Here is an Example how you can download your file Object.

But this will return nothing since the file size is too small for the system to read.

function downloadFile() {

 var file = new File(["aa"], "dek_iv.txt");
    var link = document.createElement("a");
    link.download =file.name;
    link.href = file;
    link.click();
}
<button onclick="downloadFile()">Download File</button>

Share:
14,611

Related videos on Youtube

ravindra reddy
Author by

ravindra reddy

Updated on June 04, 2022

Comments

  • ravindra reddy
    ravindra reddy almost 2 years

    I have file object

    var File = new File(["aa"], "dek_iv");
    

    can I download this one using JavaScript or jQuery

  • Harish Soni
    Harish Soni almost 6 years
    No problem. If you got the solution then if you can accept it as answer and give an upvote so that others can easily get the answer if they have the same issue.
  • ravindra reddy
    ravindra reddy almost 6 years
    But the file content is coming as html i want to see aa in the file i changed below line now its coming as text link.href = URL.createObjectURL(file);
  • Harish Soni
    Harish Soni almost 6 years
    I can't get you can you please elaborate once?
  • ravindra reddy
    ravindra reddy almost 6 years
    downloaded file is giving me html content not original content (aa) and for pdf type i am unable to open
  • Harish Soni
    Harish Soni almost 6 years
    You need to use some libraries if you want the HTML contents in a PDF file.
  • Harish Soni
    Harish Soni almost 6 years
  • Jarry
    Jarry over 5 years
    "But this will return nothing since the file size is too small for the system to read." can you expand on this? i can't find any reference to a minimum file size
  • Özgür Can Karagöz
    Özgür Can Karagöz almost 4 years
    Please enter a comment in your answer.