【问题标题】:How to fix issue when saving Excel file to users desktop?将 Excel 文件保存到用户桌面时如何解决问题?
【发布时间】:2019-08-25 09:44:15
【问题描述】:

尝试从 c# asp.net Web 应用程序将 excel 文件保存到用户桌面。这在测试时在本地机器上运行良好,但在远程服务器上运行良好。有人可以帮我解决这个问题吗?谢谢!

代码:

string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
FileInfo fi = new FileInfo(filePath + @"\spreadsheet.xlsx");
excelPackage.SaveAs(fi);

错误:

【问题讨论】:

  • 此代码在服务器上执行。您正在尝试将文件保存在服务器的“桌面”上。
  • 同意史蒂夫,但您遇到错误的路径是直接保存到 C:\,而不是桌面
  • 我觉得你们俩更让我困惑。那么,我是否应该将文件保存到服务器上的一个文件夹中,例如:c:\somefolder\,然后将文件提供给用户保存在哪里?
  • 您只能向您的用户提供一个下载按钮,让他/她决定他/她要保存文件的位置。
  • 你真的必须记住你的代码在哪里执行以及它能够做什么。此代码在服务器上运行。您是否曾经访问过一个网站,然后它只是将随机文件放在您的计算机上任意位置?不?如果网站可以做到这一点,您不认为这将代表一个巨大的安全漏洞吗?如何从网站获取计算机上的文件?该网站提供文件供下载,然后用户选择放置文件的位置。因此,您需要弄清楚如何在 ASP.NET 应用程序中提供文件以供下载。

标签: c# asp.net file-permissions


【解决方案1】:

您可能正在使用 EPPplus (excelPackage.SaveAs(fi);)。因此,如果您使用 asp.net 作为标签,则表明您可以将 Excel 文件发送到浏览器,用户将获得一个保存文件对话框。

//convert the excel package to a byte array
byte[] bin = excelPackage.GetAsByteArray();

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());

//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");

//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多