user9102141
user9102141

Reputation:

How do I make javascript download files?

I want my download link to have a custom confirmation popup but I'm not sure how to do it. I've googled but everything that comes up doesn't help. Here is what I have:

JS:

<script>
        function confirm() {
            swal({
                title: "Wait,",
                text: "Click OK to confirm that you know what you are downloading.",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
            .then((willDelete) => {
            if (willDelete) {
               //download here.
            });
            } else {
                swal("Download cancelled.");
             }
            });
        }
        </script>

HTML:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

    <div id="downloads">
            <a href="#" onclick="confirm()" class="download"><p>Dum Dum</p></a>
            <a href="FILE_downloads/iMessageSpammer.zip" download class="download"><p>iMessage Spammer</p></a>
            </div>

Does anyone know what I can do or any better methods?

Upvotes: 0

Views: 1134

Answers (3)

Zeeshan Elahi
Zeeshan Elahi

Reputation: 267

You can do it in two different ways probably.

  1. Use window.location function.
  2. Make a get request or ajax call and return that file as response.

Upvotes: 0

Stand__Sure
Stand__Sure

Reputation: 278

With HTML5 you simply add a download attribute to the anchor tag.

See MDN <a>

Upvotes: 2

I don't know if it's the best way to do it, but i use window.location="http://yourdomain.com/file=report.pdf"; It works for me. Hope it helps

Upvotes: 0

Related Questions