0

I used the following code which is working for a PDF in chrome browser

@Html.ActionLink("Download", "GetReport", new { controller = "Storage" }, new { target = "_blank" })

Here is my code inside controller

public FileResult GetReport()
{
    string ReportURL = @"C:\Tools\HazMat\HazMat\Uploads\IAC HILL TOP CAMPING LIST OF FREE ADVENTURE ACTIVITIES..pdf";
    byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);

    return File(FileBytes, "application/pdf");
}

When I gave a path related to docx file here it is downloading instead of opening the document so how can I open any kind of file in to a new tab

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Developer
  • 8,390
  • 41
  • 129
  • 238
  • 1
    `byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);` <-- Doing this is **very** inefficient - you should pass an async-capable `FileStream` to `FileResult` so it can efficiently _stream_ the response to the client asynchronously, but your code buffers the entire file into memory... and uses the (_old-hat_) synchronous (i.e. thread-blocking) `File.ReadAllBytes` method... – Dai Jul 02 '23 at 05:54
  • 2
    Out of curiosity, what makes you think browsers will display `.docx` files just like how they show PDFs? (I haven't seen a browser open Office files in-place since Office 2003 running with IE6 or maybe Office 2007 with IE7 - since then this kind of browser-based OLE is _dead_). – Dai Jul 02 '23 at 06:12

1 Answers1

0

If you set Disposition in the header it will open your file in the browser.

public FileResult GetReport()
{
 string ReportURL = @"C:\Tools\HazMat\HazMat\Uploads\IAC HILL TOP CAMPING LIST OF FREE ADVENTURE ACTIVITIES..pdf";
 byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);

 //Add this key
 Response.Headers.Add("Content-Disposition", $"inline; filename={file.FileName}.pdf");
 return File(FileBytes, "application/pdf");
}
Shervin Ivari
  • 1,759
  • 5
  • 20
  • 28
  • Will this work from word documents too? – Developer Jul 03 '23 at 11:33
  • @Developer Browsers don't have any built-in feature to render Word docs. – Shervin Ivari Jul 03 '23 at 11:43
  • @Developer, for your Word files and other formatted files which are not supported by browser you have to use tools like (viewerjs), check https://stackoverflow.com/questions/27957766/how-do-i-render-a-word-document-doc-docx-in-the-browser-using-javascript – Shervin Ivari Jul 03 '23 at 11:46