Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser download file prompt using JavaScript

I was wondering if there was any method to implement browser's download file prompt using JavaScript.

My reason - well users will be uploading files to a local fileserver which cannot be accessed from the webserver. In other words, both will be on different domains!

For example, let’s say websites hosted on www.xyz.com, but files would reside on local file server with address like \\10.10.10.01\Files\file.txt. How am I uploading/transferring file to local fileserver... using ActiveX and VBscript! (don’t ask :-)

So I am storing local file path in my database and binding that data to a grid. When the user clicks on that link, the file opens in a window (using JavaScript).

Problem is certain file types like text, jpg, pdf, etc. open inside browser window. How would I be able to implement content-type or content-disposition using client side scripting? Is that even possible?

EDIT: the local file server has a window's shared folder on which the files are saved.

like image 706
aunlead Avatar asked Apr 07 '09 18:04

aunlead


People also ask

How do I force a file to download instead of open in browser?

In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.

How do I prompt a download in HTML?

HTML: Use the anchor element download attribute to prompt the user to download a resource. The download attribute on an anchor tag pops up a Save dialog to download the resource, instead of navigating to it. e.g. Using an attribute value, such as download="cat-1.

How do you make a download link in JavaScript?

Creating the download linkCreate an object URL for the blob object. Create an anchor element ( <a></a> ) Set the href attribute of the anchor element to the created object URL. Set the download attribute to the filename of the file to be downloaded.


2 Answers

You could try using a plain hyperlink with type="application/octet-stream". Seems to work in FF, but IE and Opera ignore the attribute.

like image 64
Christoph Avatar answered Oct 13 '22 17:10

Christoph


If the file is hosted on a web server like in your example, you can do:

window.location.replace(fileUrl);

.. and the browser will figure out what to do with the file. This works great for most files, such as .xls, .csv, etc, but keep in mind that this isn't full-proof because the user's MIME handler settings will determine what to do with the file... i.e. if it is a .txt file it will most likely just be displayed in the browser and will not be given a "file download" dialogue box.

like image 23
Vince Avatar answered Oct 13 '22 17:10

Vince