2009-02-25 111 views
2

我想要做的是用戶選擇網格上的一些字段,並根據這些數據我在Web服務器上創建一個XML文件,然後我想用戶下載它就像下載任何文件一樣。但問題是,我不能使用此代碼:因爲我需要讓用戶下載3個文件,因此頭不能卡里它如何讓用戶下載一個xml文件

Response.ContentType = "APPLICATION/OCTET-STREAM"; 

     // initialize the http content-disposition header to 
     // indicate a file attachment with the default filename 
     // "myFile.txt" 
     System.String disHeader = "Attachment; Filename=\"" + fileName + 
      "\""; 
     Response.AppendHeader("Content-Disposition", disHeader); 
     FileInfo downloadFile = new FileInfo(fileFullName); 
     if (downloadFile.Exists) 
     { 
      Response.WriteFile(downloadFile.FullName); 
      HttpContext.Current.ApplicationInstance.CompleteRequest(); 
     } 

,我因子評分中獲得的文件名,並打開一個彈出窗口,列出帶有鏈接按鈕的文件名,然後用戶可以下載它。

對於每個文件我在運行時創建一個LinkBut​​ton,並添加以下代碼:

lnkProblem.Text = "Problemler dosyası"; 
    lnkProblem.Visible = true; 
    lnkProblem.Command += new CommandEventHandler(lnkUser_Command); 
    lnkProblem.CommandName = Request.QueryString["fileNameProblems"]; 
    lnkProblem.CommandArgument = Request.QueryString["fileNameProblems"]; 

然後使用此功能,使其用戶下載:

void lnkUser_Command(object sender, CommandEventArgs e) 
{ 
    Response.ContentType = "APPLICATION/XML"; 

    System.String disHeader = "Attachment; Filename=\"" + e.CommandArgument.ToString() + 
     "\""; 
    Response.AppendHeader("Content-Disposition", disHeader); 
    FileInfo downloadFile = new FileInfo(Server.MapPath(".") + "\\xmls\\" + e.CommandArgument.ToString()); 
    if (downloadFile.Exists) 
    { 
     Response.WriteFile(Server.MapPath(".") + "\\xmls\\" + e.CommandArgument.ToString()); 
     HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    } 
    HttpContext.Current.ApplicationInstance.CompleteRequest(); 
} 

應用程序創建的XML文件,但在某處,應用程序將html標籤放在該xml文件中,所以我無法打開該文件,是否有無法執行此操作?也許任何其他例子...

回答

3

的cleaneast方式將文件發送到客戶端是使用的TransmitFile方法是這樣的:

FileInfo file = new FileInfo(filePath); // full file path on disk 
Response.ClearContent(); // neded to clear previous (if any) written content 
Response.AddHeader("Content-Disposition", 
    "attachment; filename=" + file.Name); 
Response.AddHeader("Content-Length", file.Length.ToString()); 
Response.ContentType = "text/xml"; //RFC 3023 
Response.TransmitFile(file.FullName); 
Response.End(); 

對於多個文件,通常的解決辦法是打包的所有文件的zip文件,並把他們(的在這種情況下,MIME類型將是應用程序/ zip)。

+0

不工作.. :( – 2014-08-21 16:25:49

1

創建一個單獨的IHttpHandler,它只會提供您希望您的用戶下載的文件,並且RedirectlnkUser_Command中的那個處理程序。

+0

如何使用IHttpHandler?有什麼我能看的例子嗎? 謝謝 – mehmetserif 2009-02-25 15:18:46

相關問題