Response.TransmitFile不下载,并且没有抛出错误

Lan*_*ndo 7 c# httpresponse text-files transmitfile response.transmitfile

我目前正在使用HttpResponse从我的服务器下载文件.我已经有几个函数用于下载Excel/Word文件,但我无法下载简单的文本文件(.txt).

使用文本文件,我基本上将TextBox的内容转储到文件中,尝试使用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();  
}
Run Code Online (Sandbox Code Playgroud)

这里有一大堆代码不起作用.
请注意,代码运行时不会出现任何错误.文件已创建并已删除,但从未转储给用户.

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();
}
Run Code Online (Sandbox Code Playgroud)

ant*_*ode 10

这是因为您在发送之前删除了该文件.

来自MSDN - HttpResponse.End方法

将所有当前缓冲的输出发送到客户端,停止执行页面,并引发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
}
Run Code Online (Sandbox Code Playgroud)

这是我使用的Filetype方法

//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";
    }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*ris 5

我在搜索中偶然发现了这篇文章,并注意到它并没有告诉我们为什么 UpdatePanel 首先导致了这个问题。

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

触发异步回发的控件需要在UpdatePanel中做一个触发器:

<Triggers>        
<asp:PostBackTrigger ControlID="ID_of_your_control_that_causes_postback" />
</Triggers>
Run Code Online (Sandbox Code Playgroud)


Lan*_*ndo -6

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

谢谢您的帮助!

  • 感谢您让我们知道您修复了它,但没有帮助解决如何修复问题。 (4认同)