I’ve got a controller action that returns a FileResult like this
return this.File("file.pdf", "application/pdf");
for the URL “/Download/322” – where 322 is the id of the file.
This works great, so that if a user clicks on a link to the PDF – it will open in their web browser as long as they have a PDF plugin installed.
But, what if they right-click the link and choose “Save as…”? The browser pops up with the filename as “322.” I’d like to have a better filename at this point, by doing something like this:
return this.File("file.pdf", "application/pdf", "file.pdf");
But if I change the controller to return like that, then it will always pop up the download box, since MVC is setting the Content-Disposition header to attachment (so I can’t embed the file).
In summary, can I somehow detect that the user is trying to download the file vs. the file is just being embedded in something on the page?
You cannot determine how the browser has been configured to handled the document / content.
For example, one may right click on a link in an HTML document and select “Save Link As” / “Save Target As” and download the file. The link may point to another HTML document. There’s absolutely no way to determine if that happened.
The only direct way is to specify the “Content Disposition” of the response as “attachment” with a parameter “filename” with appropriate value.
Your HTML response should contain the following headers:
Example:
If browsers understand these headers – which today most of them do, they will open the dialog “Open/Save/Cancel”.
It’s similar to “Download Attachment” an image in Gmail, which otherwise, will be displayed within the browser itself.