asp.net-mvc - 将文件保存到当前用户的路径桌面
问题描述
我有一个在 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 是 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
}
}
并且由于安全原因,您只能将数据保存到下载目录。
推荐阅读
- python - 验证和测试数据的性能差异很大
- java - 减少此特定代码用于斐波那契数的时间的方法?
- c# - XNA/FNA中二维相机变换矩阵的乘法阶数
- c# - Web 表单未加载或显示
- rust - 关于何时取消引用可变引用的令人困惑的行为
- typescript - T[keyof T] 是否像分配条件类型一样工作?
- python - easybill API python,从pandas中的json中提取
- symfony - Contao > 4.3 在某些提供商上使用 sendmail 发送电子邮件会引发错误
- spring-boot - 如何使用 Spring Boot Maven 插件自动构建 Docker 映像?
- python - python无法在jupyter中导入硒