【问题标题】:.net core 2.0 Cant download file saved in folder..net core 2.0 无法下载文件夹中保存的文件。
【发布时间】:2018-12-07 15:24:30
【问题描述】:

在我想下载此文件后,我将数据网格中的信息保存到文件夹中的 xslx 文件。 我有代码,工作正常,但是在我的项目中,当我尝试下载文件时,它什么也没返回。也许是因为保护或用户角色是管理员。 我尝试过使用不同的文件夹,我确信该文件夹不是问题。 还能是什么?

 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);
            }

【问题讨论】:

  • 你要向那个函数发送什么文件路径,请写一个例子
  • fileName = "SN-export.xlsx";字符串文件路径 = _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);返回下载文件(文件路径);

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


【解决方案1】:

我已经尝试了你的代码,一切似乎都很好

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);
}

【讨论】:

  • 我也在这个简单的项目中测试了我的代码,它正在工作,我知道这一点。但它在我的项目中不起作用。我认为这可能是因为我的项目或授权中的管理员角色。不知道为什么它不起作用。
  • 如果您认为这是角色问题,请在每个方法前加上 [AllowAnonymous] 并尝试一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
相关资源
最近更新 更多