2010-09-01 85 views
1

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

我已经在开发环境中在本地系统上工作了,但我没有获得正确的文件寻址。

  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(); 
} 

同样,这个工作正常在我的本地PC,但是当我移动到服务器,我得到一个错误的访问路径。并且错误代码中列出的路径不是我想要文件去的地方。

+0

向我们展示您到目前为止的代码... – RedFilter 2010-09-01 21:08:00

+0

我将代码编辑为原始问题。 – Marc 2010-09-02 14:39:36

回答

0

您可能还需要检查并确保该帐户运行ASP.Net工作进程或合适的用户(如果您使用模拟)已向ReportFiles \ TempFiles位置写入权限。发生错误的次数很多,因为默认权限仅允许读取您网站中的文件夹。

+0

我需要在哪里授予此许可? – Marc 2010-09-02 14:39:02

+0

在文件夹本身上。通常,您可以将其授予“网络服务”或任何ASP.Net进程运行。 – 2010-09-02 16:51:53

+0

看起来像这个伎俩!谢啦! – Marc 2010-09-07 16:42:35

3

首先存储文件:

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

然后,你可以,例如,告诉浏览器重定向到文件

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

hmmmm Response.Redirect,没有想到那个。 – Marc 2010-09-01 21:23:34

相关问题