首页 > 解决方案 > 将文件保存到当前用户的路径桌面

问题描述

我有一个在 IIS 上运行的项目 ASP.NET Core 2.0 MVC。想要将数据网格中的一些信息导出到 Excel 并将其从网页保存到当前用户的桌面。

                string fileName = "SN-export-" + DateTime.Now + ".xlsx";
                Regex rgx = new Regex("[^a-zA-Z0-9 -]");
                fileName = rgx.Replace(fileName, ".");
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string fileName2 = Path.Combine(path, fileName);
                FileInfo excelFile = new FileInfo(fileName2);
                excel.SaveAs(excelFile);

这在 Visual Studio 本地完美运行,但在 IIS 上发布后就不行了。使用简单的路径字符串 path = @"C:\WINDOWS\TEMP"; 它将将此导出文件保存在服务器临时文件夹中,但不保存当前网页用户。如何得到这个?

标签: asp.net-mvciispath.net-coreexport-to-excel

解决方案


ASP.NET MVC 是 Web 应用程序的框架。所以你有前端和后端部分。此代码将在您的应用程序的服务器端执行。即使您使用 Razor 页面,它们也会在后端生成。所以有几种方法可以在电脑上保存数据:

  • 使用js迭代数据并保存,但我不确定用js保存到excel是否容易;
  • 将所需的数据发送到后端,将其保存到excel,然后返回给客户端。

对于第二种方法,您可以使用下一个代码:

[Route("api/[controller]")]
public class DownloadController : Controller {

    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(YourData data) {
        Stream stream = await {{__get_stream_based_on_your_data__}}

        if(stream == null)
            return NotFound();

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }   
}

并且由于安全原因,您只能将数据保存到下载目录。


推荐阅读