Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c# - Make a file open in browser instead of downloading it

I have an MVC project that will display some documents to users. The files are currently stored in Azure blob storage.

Currently, the documents are retrieved from the following controller action:

[GET("{zipCode}/{loanNumber}/{classification}/{fileName}")]
public ActionResult GetDocument(string zipCode, string loanNumber, string classification, string fileName)
{
    // get byte array from blob storage
    byte[] doc = _docService.GetDocument(zipCode, loanNumber, classification, fileName);
    string mimeType = "application/octet-stream";
    return File(doc, mimeType, fileName);
}

Right now, when a user clicks on a link like the following:

<a target="_blank" href="http://...controller//GetDocument?zipCode=84016&loanNumber=12345678classification=document&fileName=importantfile.pdf

Then, the file downloads to their browser's downloads folder. What I would like to happen (and I thought was default behavior) is for the file to simply be displayed in the browser.

I have tried changing the mimetype and changing the return type to FileResult instead of ActionResult, both to no avail.

How can I make the file display in the browser instead of downloading?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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);
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...