.net core 2.0无法下载文件保存在文件夹中。

时间:2018-12-07 15:24:30

标签: excel asp.net-mvc download asp.net-core-2.0

我要下载此文件后,将信息从datagrid保存到该文件夹​​中的xslx文件中。 我有代码,可以正常工作,但是在我的项目中,当我尝试下载文件时,它什么也没有返回。也许是由于保护或用户角色是admin。 我尝试使用其他文件夹,但我确定该文件夹不是问题。 还有什么呢?

 public FileResult downloadFile(string filePath)
            {
                IFileProvider provider = new PhysicalFileProvider(filePath);
                IFileInfo fileInfo = provider.GetFileInfo(fileName);
                var readStream = fileInfo.CreateReadStream();
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(readStream, mimeType, fileName);
            }

1 个答案:

答案 0 :(得分:0)

我尝试了您的代码,一切似乎都很好

public IActionResult Index()
{
    var fileName = "SN-export.xlsx";
    string filePath = _hostingEnvironment.WebRootPath;
    string fileName2 = Path.Combine(filePath, fileName);
    FileInfo excelFile = new FileInfo(fileName2);
    if (excelFile.Exists) {
        excelFile.Delete();
        excelFile =  new FileInfo(fileName2);
    }
    // excel.SaveAs(excelFile); Have to comment this because i don't know what excel nuget you are using
    // For testing purpose i have used the following two lines
    var file = System.IO.File.Create(excelFile.ToString());
    file.Close();
    return DownloadFile(filePath, fileName);
}

public FileResult DownloadFile(string filePath,string fileName)
{ 
    IFileProvider provider = new PhysicalFileProvider(filePath);
    IFileInfo fileInfo = provider.GetFileInfo(fileName);
    var readStream = fileInfo.CreateReadStream();
    var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    return File(readStream, mimeType, fileName);
}