views:

23

answers:

3

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?

A: 

Well, after some more thought, I've decided I'll just provide the filename every time. The only disadvantage is it will be marked as an attachment, and therefore won't load in the browser (instead, the user will download the file).

Plus, I don't really think you can do what I'm asking above... so unless someone has any other ideas... I'll accept this answer.

davekaro
+3  A: 

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:

Content-Type: whatever/be-it
Content-Disposition: attachment; filename=FilenameToSaveAs.Ext

Example:

Content-Type: text/html
Content-Disposition: attachment; filename=mypage.html

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.

MasterGaurav
Exactly. Good explanation of what's going on. It just further reinforces that I have to chose one way. Either specify it as an attachment, or not.
davekaro
Agree to what you've said!
MasterGaurav
+1  A: 

Posting another answer... coz formatting doesn't work in comments.

One thought came to my mind... of using JavaScript.

For enforcing download:

<a href='downloadFile.ext'
   onclick="alert('This file cannot be shown, right click, select Save Target As to download');
    return false'>
  Text for link</a>

For view or download:

   <a href="simpleFile.ext">Text for Link</a>

In the second case, the user may either click and let browser handle by default or right-click and save!

MasterGaurav