【问题标题】:Save file to path desktop for current user将文件保存到当前用户的路径桌面
【发布时间】:2019-04-30 13:02:21
【问题描述】:

我有一个在 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-mvc iis path .net-core export-to-excel


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多