代码之家  ›  专栏  ›  技术社区  ›  Marc

将文件存储在ASP.net网站,然后下载到浏览器

  •  1
  • Marc  · 技术社区  · 14 年前

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

    我已经在dev环境中的本地系统上运行了它,但是我没有得到正确的文件地址。

    1. 如何将文件存储在“~\ParentFolder\SubFolder”中\文件.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();
    }
    

    2 回复  |  直到 14 年前
        1
  •  0
  •   Dillie-O    14 年前

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

        2
  •  3
  •   M4N    14 年前

    首先存储文件:

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

    例如,您可以告诉浏览器重定向到该文件

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