6

我目前使用HttpResponse从我的服务器上下载文件。我已经有一些功能用于下载Excel/Word文件,但是我无法让我的简单文本文件(.txt)下载。Response.TransmitFile不下载,并没有错误

对于文本文件,我基本上将文本框的内容转储到文件中,试图用HttpResponse下载文件,然后删除临时文本文件。

这里是为Excel/Word文档工作的我的代码示例:

protected void linkInstructions_Click(object sender, EventArgs e) 
{ 
    String FileName = "BulkAdd_Instructions.doc"; 
    String FilePath = Server.MapPath("~/TempFiles/BulkAdd_Instructions.doc"); 
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
    response.ClearContent(); 
    response.Clear(); 
    response.ContentType = "application/x-unknown"; 
    response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); 
    response.TransmitFile(FilePath); 
    response.Flush(); 
    response.End(); 
} 

这里是代码不起作用块。
注意代码运行时不会引发任何错误。该文件已创建,并已删除,但从未转储给用户。

protected void saveLog(object sender, EventArgs e) 
{ 
    string date = DateTime.Now.ToString("MM_dd_yyyy_hhmm");  // Get Date/Time 
    string fileName = "BulkLog_"+ date + ".txt";    // Stitch File Name + Date/Time 
    string logText = errorLog.Text;        // Get Text from TextBox 
    string halfPath = "~/TempFiles/" + fileName;    // Add File Name to Path 
    string mappedPath = Server.MapPath(halfPath);    // Create Full Path 

    File.WriteAllText(mappedPath, logText);      // Write All Text to File 

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
    response.ClearContent(); 
    response.Clear(); 
    response.ContentType = "text/plain"; 
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
    response.TransmitFile(mappedPath);    // Transmit File 
    response.Flush(); 

    System.IO.File.Delete(mappedPath);    // Delete Temporary Log 
    response.End(); 
} 

回答

-5

我最终固定在我自己的问题。事实证明,这是一个Ajax问题,不允许我的Button正确回发。这阻止了TransmitFile被触发。

感谢您的帮助!

+0

你是如何解决它的?我有完全相同的问题。我的ModalpopupExtender/UpdatePanel阻止我的按钮启动我的文档下载工作。当我移动我的modalpopupextender/updatepanel之外的那个按钮时,它完美地工作。 – JoeManiaci 2016-02-16 18:18:15

+3

谢谢你让我们知道你解决了它,而不是帮助如何。 – Danrex 2016-02-24 20:33:46

+0

告诉我们如何修复它本来不错 – Nevyn 2016-11-17 20:53:11

10

这是因为您正在删除文件才能发送。

从MSDN - HttpResponse.End Method

发送当前所有缓冲的输出 客户端,停止 页的执行,并引发EndRequest事件。

尝试把你的System.IO.File.Delete(mappedPath);在response.End()之后行。在我的测试中,它似乎正在工作。

此外,检查文件是否先存在,不能看到任何文件,可能是一个好主意。在那里存在,不想要任何空引用异常,并设置Content-Length。

编辑:这里是我在前段时间在工作中使用的代码,可能会帮助你一点。

// Get the physical Path of the file 
string filepath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + folder + filename; 

// Create New instance of FileInfo class to get the properties of the file being downloaded 
FileInfo file = new FileInfo(filepath); 

// Checking if file exists 
if (file.Exists) 
{        
    // Clear the content of the response 
    Response.ClearContent(); 

    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header 
    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name)); 

    // Add the file size into the response header 
    Response.AddHeader("Content-Length", file.Length.ToString()); 

    // Set the ContentType 
    Response.ContentType = ReturnFiletype(file.Extension.ToLower()); 

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead) 
    Response.TransmitFile(file.FullName); 

    // End the response 
    Response.End(); 

    //send statistics to the class 
} 

这里是文件类型的方法我用

//return the filetype to tell the browser. 
//defaults to "application/octet-stream" if it cant find a match, as this works for all file types. 
public static string ReturnFiletype(string fileExtension) 
{ 
    switch (fileExtension) 
    { 
     case ".htm": 
     case ".html": 
     case ".log": 
      return "text/HTML"; 
     case ".txt": 
      return "text/plain"; 
     case ".doc": 
      return "application/ms-word"; 
     case ".tiff": 
     case ".tif": 
      return "image/tiff"; 
     case ".asf": 
      return "video/x-ms-asf"; 
     case ".avi": 
      return "video/avi"; 
     case ".zip": 
      return "application/zip"; 
     case ".xls": 
     case ".csv": 
      return "application/vnd.ms-excel"; 
     case ".gif": 
      return "image/gif"; 
     case ".jpg": 
     case "jpeg": 
      return "image/jpeg"; 
     case ".bmp": 
      return "image/bmp"; 
     case ".wav": 
      return "audio/wav"; 
     case ".mp3": 
      return "audio/mpeg3"; 
     case ".mpg": 
     case "mpeg": 
      return "video/mpeg"; 
     case ".rtf": 
      return "application/rtf"; 
     case ".asp": 
      return "text/asp"; 
     case ".pdf": 
      return "application/pdf"; 
     case ".fdf": 
      return "application/vnd.fdf"; 
     case ".ppt": 
      return "application/mspowerpoint"; 
     case ".dwg": 
      return "image/vnd.dwg"; 
     case ".msg": 
      return "application/msoutlook"; 
     case ".xml": 
     case ".sdxl": 
      return "application/xml"; 
     case ".xdp": 
      return "application/vnd.adobe.xdp+xml"; 
     default: 
      return "application/octet-stream"; 
    } 
} 
+0

不幸的是我也有最初尝试这个。在我的情况下,当在delete.End()下面移动Delete行时,它会完全跳过Delete行,并在response.End()处打破。我也尝试彻底删除删除行,但仍然没有运气。 – Lando 2011-03-30 14:43:37

2

非常感谢您跟进您的问题。我花了几个小时试图弄清楚为什么没有发生任何错误代码被抛出。原来,这是我的AJAX UpdatePanel神秘而隐蔽的方式。

0

也尝试this用于在客户端(仅限Chrome现在)保存文本,而无需往返服务器。

Here是另一个Flash基地之一......

1

我碰到这个岗位绊倒在我的搜索,并发现它是不是在告诉我们有用为什么在UpdatePanel首先导致此问题。

UpdatePanel是一个异步回发,并且Response.TransmitFile需要完整的回发才能正常工作。

触发异步回送需要在UpdatePanel来进行触发控制:

<Triggers>   
<asp:PostBackTrigger ControlID="ID_of_your_control_that_causes_postback" /> 
</Triggers>