0

I have this code:

   public void OpenFile(string fileName)
        {
            var url = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            using (var fileStream =  new FileStream(url, FileMode.Open))
            {
                byte[] bytes = new byte[fileStream.Length];
                int numBytesToRead = (int)fileStream.Length;
                int numBytesRead = 0;
                fileStream.Read(bytes,numBytesRead, numBytesToRead);              
            }
        }

That code is working fine, but I want to show that file in the browser, I'm executing this method on click in the name of the file, parameters are working great, which is the other code that I need to put to show the file in the browser? Mostly the files are going to be .doc and .pdf. How can I show the documents in the browser??

AlexGH
  • 2,433
  • 5
  • 31
  • 63

1 Answers1

0

You can return a FileStreamResult from your action method. Change the method return type from void to ActionResult

public ActionResult OpenFile(string fileName)
{
   var pathToTheFile = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
   var fileStream = new FileStream(pathToTheFile,
                                    FileMode.Open,
                                    FileAccess.Read
                                );
   return  new FileStreamResult(fileStream,  MimeMapping.GetMimeMapping(fileName));    
}
Shyju
  • 197,032
  • 96
  • 389
  • 477