简体   繁体   English

使用ASP.NET Core下载文件

[英]Download file using ASP.NET Core

I´m trying to download a excel file after the file is created and I´m having the following error: 创建文件后,我尝试下载excel文件,但出现以下错误:

UnauthorizedAccessException: Access to the path 'C:\\Users\\user_name\\Documents\\Visual Studio 2015\\Projects\\Project_Name\\src\\Project_Name\\wwwroot' is denied. UnauthorizedAccessException:拒绝访问路径“ C:\\ Users \\用户名\\ Documents \\ Visual Studio 2015 \\ Projects \\ Project_Name \\ src \\ Project_Name \\ wwwroot”。

The file is created successfully, the problem is in the download method. 文件创建成功,问题出在下载方法中。

I already try to solve this error doing the following actions: 我已经尝试执行以下操作来解决此错误:

  • Open VS as Admin 以管理员身份打开VS
  • Add IIS_IUSR user to the project folder 将IIS_IUSR用户添加到项目文件夹

Here´s the code: 这是代码:

    private readonly IHostingEnvironment _hostingEnvironment;
    public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    public void createFile()
    {
        string wwwrootPath = _hostingEnvironment.WebRootPath;
        string fileName = @"Employees.xlsx";
        FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));

        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(wwwrootPath, fileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save(); 
            downloadFile(wwwrootPath);

        }  

}
    public FileResult downloadFile(string filePath)
    {
        var mimeType = "application/vnd.ms-excel";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        return File(fileStream, mimeType, "Employees.xlsx");
    }

Note: I didn´t make the deploy of the project in IIS. 注意:我没有在IIS中进行项目的部署。

Best Regards 最好的祝福

In ASP.NET Core you should use PhysicalFileProvider class to access the actual system's files. 在ASP.NET Core中,应使用PhysicalFileProvider类访问实际系统的文件。 If you look into File providers section in the documentation: 如果您查看文档中的“ 文件提供者”部分:

The PhysicalFileProvider provides access to the physical file system. PhysicalFileProvider提供对物理文件系统的访问。 It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. 它包装System.IO.File类型(用于物理提供程序),对目录及其子目录的所有路径进行范围界定。 This scoping limits access to a certain directory and its children, preventing access to the file system outside of this boundary. 这种作用域限制了对某个目录及其子目录的访问,从而阻止了对该边界之外文件系统的访问。

The following should work for you: 以下应该为您工作:

string wwwrootPath = _hostingEnvironment.WebRootPath;
string fileName = @"Employees.xlsx";

IFileProvider provider = new PhysicalFileProvider(wwwrootPath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();

// PhysicalFileProvider.GetFileInfo returns instance of PhysicalFileInfo that provides implementation of IFileInfo.CreateReadStream method. // PhysicalFileProvider.GetFileInfo返回的实例PhysicalFileInfo提供实现IFileInfo.CreateReadStream方法。

I test your code and the error is gone, but the file is not being downloaded. 我测试了您的代码,错误消失了,但是文件没有被下载。 Here is the code: 这是代码:

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.ms-excel";
        return File(readStream, mimeType, fileName);
}

Best Regards 最好的祝福

I noticed two situations in my code. 我在代码中注意到了两种情况。 1 - If I call the download method directly in my button the download happens, but the file is stored in localhost directory, something like http://localhost:3724/Area/Controller/downLoadMethod . 1-如果直接在按钮中调用下载方法,则会进行下载,但是文件存储在localhost目录中,例如http:// localhost:3724 / Area / Controller / downLoadMethod I want the browser to open de download box and then I choose the place to store the file. 我希望浏览器打开下载框,然后选择存储文件的位置。

2 - If in my button I call the exportMethod and inside of the exportMethod I call the downloadMethod after the file is exported I just get a blank page, the download does't happen. 2-如果在我的按钮中调用了exportMethod,而在exportMethod的内部调用了downloadMethod,则在文件导出后我只会得到一个空白页,则不会进行下载。

Best Regards 最好的祝福

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM