Being a web developer, you must have worked one or more times on providing feature for downloading a file. If not, you’ll work in near future. Anyways let’s discuss a scenario.
Normally, we see that when we click on a link of the file to download that link opens up in the browser. Actually when we click on the link, request is sent to web server, and server returns the content to the client. Based on the file name extension, browser decides the type of content and accordingly, if browser has a capability to load the file on browser that it shows it in the browser. If browser is not able to display on the browser the shows the download file dialog box to save it. You may see different behavior in different browser because some browser may able to show it on browser and other may show the download dialog box. But you can save it via browser save as option if it is rendered on browser.
But How to forcefully show the save as dialog to the user?
As we already discussed that when we click the on any link then based on the browser capability the browser shows the dialog box or open it in the browser itself. But to show the save as dialog every time (for every type of file) we need to to tell browser that this is an attachment. For this we need to add a Content-Disposition Header in the response. This should be as
You can write the code to download the file many ways. But if you want to download it using the browser’s download dialog box then we need to add Content-Disposition Header. We can write the code for downloading a file as
Once you add the Content-Disposition header, the file will always be downloaded. As the behavior of browsers varies as Firefox shows a save as dialog, Internet Explorer (v11) prompts at the bottom side of browser, while Google chrome downloads it without prompting but in any case file will be downloaded.
Thanks for reading the post.