{"id":6680,"date":"2018-09-01T04:32:50","date_gmt":"2018-09-01T08:32:50","guid":{"rendered":"http:\/\/local.brightwhiz\/?p=6680"},"modified":"2021-12-08T11:34:05","modified_gmt":"2021-12-08T16:34:05","slug":"how-to-forcefully-download-a-file-from-a-link","status":"publish","type":"post","link":"http:\/\/local.brightwhiz\/how-to-forcefully-download-a-file-from-a-link\/","title":{"rendered":"How to Forcefully Download a File From a Link"},"content":{"rendered":"\n
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.<\/p>\n\n\n\n
This is particularly common with image files, plain text files, and pdf documents among others.<\/p>\n\n\n\n
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…<\/strong>“. On Mac or mobile devices, you click and hold on the link to reveal the said option.<\/p>\n\n\n\n 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.<\/p>\n\n\n\n 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.<\/p>\n\n\n\n The HTML anchor download attribute can be used in two ways as follows:<\/p>\n\n\n\n or<\/p>\n\n\n\n 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 server with random characters.<\/p>\n\n\n\n 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.<\/p>\n\n\n\n The server method can be used where the HTML<\/a> method does not work. Browsers like IE and Safari may not work with the HTML method.<\/p>\n\n\n\nForcefully Download a File by Default<\/h2>\n\n\n\n
Using HTML Tag Attributes<\/h2>\n\n\n\n
<a href="file.txt" download="">Click here<\/a><\/code><\/pre>\n\n\n\n
<a href="test.txt" download="alternatefilename.txt">Click here<\/a><\/code><\/pre>\n\n\n\n
Using the Content-Disposition HTTP Header<\/h2>\n\n\n\n