Make a file open in browser instead of downloading it

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Make a file open in browser instead of downloading it

Message par ForumBot »

Make a file open in browser instead of downloading it
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Make a file open in browser instead of downloading it

Message par ForumBot »

Thanks to all the answers, the solution was a combination of all of them.

First, because I was using a `byte[]` the controller action needed to be `FileContentResult` not just `FileResult`. Found this thanks to: [What's the difference between the four File Results in ASP.NET MVC](https://stackoverflow.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc)

Second, the mime type needed to NOT be a `octet-stream`. Supposedly, using the stream causes the browser to just download the file. I had to change the type `application/pdf`. I will need to explore a more robust solution to handle other file/mime types though.

Third, I had to add a header that changed the `content-disposition` to `inline`. Using [this post](https://stackoverflow.com/questions/6293893/how-to-force-pdf-files-to-open-in-browser) I figured out I had to modify my code to prevent duplicate headers, since the content-disposition was already being set to `attachment`.

The successful code:

```
public FileContentResult GetDocument(string zipCode, string loanNumber, string classification, string fileName)
{
byte[] doc = _docService.GetDocument(zipCode, loanNumber, classification, fileName);
string mimeType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName);
return File(doc, mimeType);
}

```
Répondre

Revenir à « Azure Infrastructure »