0

We have a module to generate and store report in PDF format.

The url to get document for example like this:

https://domain.com/Document/GetDocument?documentId=00000000-0000-0000-0000-000000000000

This url will return a document with name: Document_UserName_Date.

However, since there are browser can view PDF file like Chrome, the document will be view right in a tab of browser with above url.

So, when users try to save that document in their computers, the default file name(which get from url) is: https___domain.com.pdf instead of Document_UserName_Date.pdf as we expected. So I'm thinking, if I can just changed the url into:

https://domain.com/Document/Document_UserName_Date.pdf

my problem will be solved.

3
  • 1
    Have you tried setting the content type to application/pdf in your response? Commented Mar 3, 2013 at 8:15
  • The user also likes to view the document with browsers. That's why I'd like to change the url in the first place Commented Mar 3, 2013 at 8:31
  • Changing the url to have a '.pdf' extension alone might not solve your problem. You should set the right headers, as Darin mentions below. Commented Mar 3, 2013 at 8:36

1 Answer 1

2

In order to avoid the document being shown in the browser, but the user directly prompted to download it, you could use set the Content-Disposition header to attachment:

Content-Disposition: attachment; filename="Document_UserName_Date.pdf"

This could be done by simply passing the filename as third argument to the File overload:

public ActionResult GetDocument(Guid documentId)
{
    byte[] document = GetDocument(documentId);
    return File(document, "application/pdf", "Document_UserName_Date.pdf");
}

UPDATE:

If you want the user to view the document inline in his browser then you could use routing and define the following route:

routes.MapRoute(
    "ViewPdfRoute",
    "document/{id}/{name}.pdf",
    new { controller = "Home", action = "GetDocument" }
);

and in your controller action:

public ActionResult GetDocument(Guid id, string name)
{
    byte[] pdf = GetDocument(id);
    return File(pdf, "application/pdf");
}

And finally you could request a document like this:

http://domain.com/document/0DF7E254-0576-4BC0-8B05-34FC0F5246A2/document_username_date.pdf
Sign up to request clarification or add additional context in comments.

3 Comments

The user also likes to view the document with browsers.That's why I'd like to change the url in the first place
I think Content Type and Content Disposition headers are the key. Athough, I have noted that some of the older browsers do not support inline viewing of PDF.
Thanks guys, I'll try it as the first thing to do at office tomorrow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.