Navya
Navya

Reputation: 727

Force Download a file in Javascript

I want to make a function which will forcefully download a file on client side wothout help of server. The following function is not working and showing the error that header is undefined. Help would be appreciated.

function download() {

   var url = "C:\Koala.jpeg";
   var request = new XMLHttpRequest();
   header("Content-Type: application/force-download");
   header("Content-disposition: attachment; filename=url");
   header("Content-type: application/octet-stream");

       window.open(url, 'Download');
}

Upvotes: 0

Views: 3276

Answers (2)

Triforcey
Triforcey

Reputation: 451

This actually IS possible, and the solution I came up with is extremely simple. In html the a tag, if it has a download attribute, it will download the file, not view it. We can use this and have an a tag with the download attribute and the hidden attribute, and then activate it with JavaScript by faking a click on it. The following code snippet should download a cat picture.

document.getElementById('download').click();
<a id="download" href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download hidden></a>

Upvotes: 0

Nico
Nico

Reputation: 12683

This is not going to be possible in this fashion. In your JavaScript fashion you are telling the browser to force download a file of a path of C:\Koala.jpeg. Not only that but you aren't doing anything with the request object, and as far as I can tell the function header() doesn't exist.

This means that the browser must download a file from your local file system. Thus giving script access to your file system. This is a major security problem and will never happen.

Now if what you really want to do is download a file from the remote server you need to instruct your web server to push a file down using standard methods to download a file. Although the user will still have the ability to cancel the download as you (as the developer) cant force a user to do anything to their file system without their permission.

To download the file from your web-server will require knowledge of your environment so we may point you in the right direction.

Cheers.

Upvotes: 1

Related Questions