【问题标题】:Store files in ASP.net website, then download to browser将文件存储在 ASP.net 网站,然后下载到浏览器
【发布时间】:2010-09-01 21:06:24
【问题描述】:

我正在我的 asp.net 网站上用 C# 创建一个 Excel 文件。然后,我想将此文件保存在 Web 服务器文件中的某个位置,并将该文件发送到浏览器供用户下载。

我已经让它在开发环境中的本地系统上运行,但我没有正确获取文件寻址。

  1. 如何将文件存储在“~\ParentFolder\SubFolder\file.ext”中。
  2. 然后将该文件发送到浏览器供用户下载。

任何指导将不胜感激。

        String outputFile = Utilities.writeToExcelFile("", MapPath(@"~\ReportFiles\TempFiles\DropShipData.xls"), table);

    DownloadFile(outputFile);


       public void DownloadFile(string fname)
{
    string path = fname;
    string name = Path.GetFileName(path);
    string ext = Path.GetExtension(path);
    string type = "";
    // set known types based on file extension  
    if (ext != null)
    {
        switch (ext.ToLower())
        {
            case ".htm":
            case ".html":
            case ".aspx":
            case ".asp":
                type = "text/HTML";
                break;

            case ".xls":
            case ".xlsx":
            case ".csv":
                type = "Application/x-msexcel";
                break;

            case ".pdf":
                type = "Application/pdf";
                break;

            case ".txt":
                type = "text/plain";
                break;

            case ".doc":
            case ".docx":
            case ".rtf":
                type = "Application/msword";
                break;
        }
    }

    Response.AppendHeader("content-disposition",
        "attachment; filename=" + name);

    if (type != "")
        Response.ContentType = type;
    Response.WriteFile(path);
    Response.End();
}

同样,这在我的本地电脑上运行良好,但是当我将它移动到服务器时,访问路径时出现错误。并且错误代码中列出的路径不是我想要文件去的地方。

【问题讨论】:

  • 向我们展示您目前拥有的代码...
  • 我将代码编辑成原始问题。

标签: c# asp.net response


【解决方案1】:

先存储文件:

string physicalPath = Server.MapPath("~/ParentFolder/SubFolder/file.ext");
// returns c:\path\to\website\ParentFolder\SubFolder\file.ext

然后你可以告诉浏览器重定向到那个文件

Response.Redirect("~/ParentFolder/SubFolder/file.ext");

【讨论】:

  • hmmmm Response.Redirect,没想到那个。
【解决方案2】:

您可能还需要检查并确保运行 ASP.Net 工作进程的帐户或相应的用户(如果您使用模拟)具有对 ReportFiles\TempFiles 位置的写入权限。很多时候发生错误是因为默认权限仅授予对您网站中的文件夹的读取权限。

【讨论】:

  • 我需要在哪里授予此权限?
  • 文件夹本身。通常,您会将其授予“网络服务”或任何 ASP.Net 进程在其下运行。
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 2015-08-08
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 2021-08-15
相关资源
最近更新 更多