Have you ever tried to forcefully download a file from a website? Of course, you have. Most times all you get is a browser that insists on displaying the file rather than giving you the option to save it to your device.
This is particularly common with image files, plain text files, and pdf documents among others.
For the somewhat savvy web surfer, there is a quite simple workaround. All you need to do is right-click on the URL and choose the option that says “save link as…“. On Mac or mobile devices, you click and hold on the link to reveal the said option.
Forcefully Download a File by Default
Now that we’ve seen how the end user can forcefully download a file from a website, it is good to know that this feature can be controlled by the web developer using two main methods.
Using HTML Tag Attributes
The web developer can add an attribute to the URL anchor tag that will tell the web browser how to treat the target of the link. The attribute, in this case, it the “download” attribute.
The HTML anchor download attribute can be used in two ways as follows:
<a href="file.txt" download="">Click here</a>
<a href="test.txt" download="alternatefilename.txt">Click here</a>
The first option will download and prompt to save the file with its current filename. The second option will save the file with the name specified by the attribute. The latter is significant when you want to sanitize the file name of the download. This could be an example where the file could be stored on a A server is a computer application program that responds to requests for information from a client in a client/server relationship system. A typical example is a web server or pushing a web page to a web browser or a web server receiving email and transferring it to an email client. A server can also refer to the actual hardware designed... More with random characters.
Using the Content-Disposition HTTP Header
The web developer can also send headers along with the file which will tell the web browser that you intend for the link target to be downloaded by default.
The server method can be used where the HTML method does not work. Browsers like IE and Safari may not work with the HTML method.
Here is how we can force a file download from the server. This example uses PHP.
<?php header("Content-Disposition: attachment"); readfile("filename.txt"); ?>
You need to set the Content-Disposition header to “attachment”. The other option is inline or simply omit the header. You can change the filename using the following modified Content-Disposition.
<?php header("Content-Disposition: attachment; filename=newfilename.txt"); readfile("filename.txt"); ?>
There you have it. You now have the skills you need to control how your website visitors can forcefully download a file when the situation calls for it.