0

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');
}

2 Answers 2

1

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.

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

Comments

0

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>

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.