将文件保存到当前用户的路径桌面
Save file to path desktop for current user
我在 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然后return到客户端。
对于第二种方法,您可以使用下一个代码:
[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
}
}
并且出于安全原因,您只能将数据保存到下载目录。
我在 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然后return到客户端。
对于第二种方法,您可以使用下一个代码:
[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
}
}
并且出于安全原因,您只能将数据保存到下载目录。