在ASP.NET Core中,使用FileStream和FileResult两种方式来返回文件内容,但两者的结果可能不同。如果想要正确地返回文件内容,可以使用以下代码:
public IActionResult DownloadFile(string path)
{
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
stream.CopyTo(memory);
}
memory.Position = 0;
var extension = Path.GetExtension(path);
var contentType = GetContentType(extension);
return File(memory, contentType, Path.GetFileName(path));
}
在这个示例中,我们使用MemoryStream来读取文件并返回内容; 我们还需要定义GetContentType方法来获取文件的类型,如下所示:
private string GetContentType(string extension)
{
switch (extension.ToLower())
{
case ".txt":
return "text/plain";
case ".pdf":
return "application/pdf";
case ".doc":
case ".docx":
return "application/vnd.ms-word";
case ".xls":
case ".xlsx":
return "application/vnd.ms-excel";
case ".png":
return "image/png";
case ".jpg":
case ".jpeg":
return "image/jpeg";
default:
return "application/octet-stream";
}
}
这样,我们就可以正确地返回文件内容并获取到文件的类型了。