在浏览器c#中显示文件
本文关键字:显示文件 浏览器 | 更新日期: 2023-09-27 18:14:08
我有这样的代码:
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);
}
}
代码运行正常,但我想在浏览器中显示文件,我在click上执行这个方法在文件名中,参数运行良好,我还需要哪段代码来在浏览器中显示文件?大多数文件都是。doc和。pdf。我如何在浏览器中显示文档??
您可以从您的操作方法返回一个FileStreamResult
。将方法返回类型从void
更改为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));
}