How to download doc, excel or pdf files using Javascript?

Dung Do Tien Mar 12 2021 275

I have a pdf path file, I want to download it directly after call API.

$.post(form.attr('action'), data, function (response) {
    if (response !== null && response.Success) {
        window.location.href = response.Data; // response.Data = "https://example.com/file/report.pdf"
    }
});

I use window.location.href but it does not work for me

Have 2 answer(s) found.
  • D

    Dương Trang Quốc Mar 12 2021

    You can use <iframe> to help download file such as below:

    <iframe id="your_iframe" style="display:none;"></iframe>
    <script>
        function Download(url) {
            document.getElementById('your_iframe').src = url;
        };
        
        var url ="http://example.com/statics/file_name.pdf";
        Download(url);
        
    </script>

    I hope it work for you.

  • N

    Nguyen Truong Giang Mar 12 2021

    I use as below it worked for me.

    window.open(your_url, '_blank');
    
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close