Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Is there a way to stream a file using ASP.NET MVC FileContentResult within the browser with a specific name?

I have noticed that you can either have a FileDialog (Open/Save) or you can stream the file in a browser window, but then it will use the ActionName when you try to save the file.

I have the following scenario:

byte[] contents = DocumentServiceInstance.CreateDocument(orderId, EPrintTypes.Quote); result = File(contents, "application/pdf", String.Format("Quote{0}.pdf", orderId)); 

When I use this, I can stream the bytes, but a OPEN/SAVE file dialog is given to the user. I would like to actually stream this file in a browser window.

If I just use the FilePathResult, it shows the file in a browser window, but then when I click on "Save" button to save the file in PDF, it shows me the Action Name as the name of the file.

Has anyone encountered this?

like image 324
Anup Marwadi Avatar asked Jul 08 '10 18:07

Anup Marwadi


2 Answers

public ActionResult Index() {     byte[] contents = FetchPdfBytes();     return File(contents, "application/pdf", "test.pdf"); } 

and for opening the PDF inside the browser you will need to set the Content-Disposition header:

public ActionResult Index() {     byte[] contents = FetchPdfBytes();     Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");     return File(contents, "application/pdf"); } 
like image 117
Darin Dimitrov Avatar answered Oct 05 '22 15:10

Darin Dimitrov


Actually, the absolutely easiest way is to do the following...

byte[] content = your_byte[];  FileContentResult result = new FileContentResult(content, "application/octet-stream")  {   FileDownloadName = "your_file_name" };  return result; 
like image 22
azarc3 Avatar answered Oct 05 '22 14:10

azarc3