替代Response.TransmitFile() [英] Alternatives to Response.TransmitFile()

查看:192
本文介绍了替代Response.TransmitFile()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我设置code我一直在玩弄在过去的几天,我需要从服务器到客户端下载文件。这是比较容易的部分,但我也需要刷新网格视图,它的完成,并在该文件已成功创建了警报显示后,但每次我发现要下载的方式包含code的选线,将是我的垮台。

到Response.End()

Response.Close()或

ApplicationInstance.CompleteRequest()

所有这些结束当前的反应或相信在ApplicationInstance的情况下,它刷新页面,我试图下载的文本文件的所有源$ C ​​$ C。在此之后是code我有一个从服务器下载一个文件,下面的代码片段是我下载文件的源。如果您有任何可以帮助解决这个无尽梦魇这将会是很大的AP preciated。

  //我在一个ArrayList一起带来的一切写入文件。
            asfinalLines = alLines.ToArray(typeof运算(字符串))作为字符串[];            字符串的文件路径= HttpContext.Current.Server.MapPath(〜/温度/);
            字符串文件名=的test.txt;            //创建在服务器上的文件
            File.WriteAllLines(文件路径+文件名,asfinalLines);            //提示用户保存文件
            System.Web.Htt presponse响应= System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType =text / plain的;
            response.AppendHeader(内容处置,附件;文件名=+文件名+;);
            response.TransmitFile(文件路径+文件名);
            response.Flush();            //删除服务器上的文件
            File.Delete(文件路径+文件名);            response.Close();


解决方案

方法1: 使用临时文件的结果
如果你只是想删除的文件的文件传输后,或执行其他一些清理工作可能做到这一点。

  //生成你的文件
//设置文件路径和文件名变量
字符串stFile =文件路径文件名+;
尝试{
    response.Clear();
    response.ContentType =text / plain的;
    response.AppendHeader(内容处置,附件;文件名=+文件名+;);
    response.TransmitFile(stFile);
    response.Flush();
}赶上(例外前){
    //任何的错误处理机制
} {最后
    如果(System.IO.File.Exists(stFile)){
        System.IO.File.Delete(stFile);
    }
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

方法二:不保存文件到服务器的结果
如果您的文本数据是小,您可以按照另一种(不要使用这种方法来传输大量数据),可以直接提供上下文为文本文件到客户端,而在它们保存到服务器

  {尝试
    //假设asFinalLines是一个字符串变量
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader(内容长度,asFinalLines.Length.ToString());
    Response.ContentType =text / plain的;
    response.AppendHeader(内容处置,附件;文件名=+文件名+;);
    的Response.Write(asFinalLines);
    response.Flush();
}赶上(例外前){
    Debug.Print(asFinalLines);
} {最后
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

PS:我是一个VB.NET的人,试图把code以上的转换在C#中,可能有一些区分大小写的问题,但逻辑是非常清楚的。

更新:

方法3: 执行其他code。与文件传输的结果
但必须记住的是,你不能有一个请求多个响应。您无法更新您的网页,并在一个单一的响应传送文件。标头可以设置每个请求一次。

在这种情况下,你必须遵循这一方法:


  • 创建一个新的 DIV /标签在那里你会显示一个链接下载的文件。保持它的隐藏默认情况下。

  • 处理请求

  • 生成所需的文件(不传输然而,仅保存到服务器)

  • 执行其他任务,更新您的前端(即刷新网格,显示信息等),也

  • 提供在隐藏标签的链接生成的文件并显示它。 (您也可以使用您的信息div来提供下载链接。

  • 在从previous步显示的链接下载请求传送文件,然后删除它作为方法1中提到(不要再生,只能传输/删除)。

  • 另外,您可以删除旧文件处理之前并生成新文件。通过这种方式可以让用户直到产生一个新的文件下载旧的文件。这种方法更适合于大型文件。

此方法增加了额外的步骤,生成后下载该文件,不支持的直接数据传输,即没有它保存到服务器上。

So I have the set of code I've been toying with for the past couple days, I need to download a file from the server to the client. That's the easy part, but I also need to refresh a grid view after it's finished and display in an alert that the file has been successfully created, but every way that I've found to download contains a select line of code which will be my downfall.

Response.End()

Response.Close() or

ApplicationInstance.CompleteRequest()

All of these end the current response or I believe in ApplicationInstance's case it flushes all the source code of the page to the text file I'm attempting to download. Following this is the snippet of code I have for downloading a file from the server, following is the source for downloading my file. If you have anything that can help solve this never ending nightmare it'd be greatly appreciated.

            //I brought everything together in an arraylist to write to file.
            asfinalLines = alLines.ToArray(typeof(string)) as string[];

            string FilePath = HttpContext.Current.Server.MapPath("~/Temp/");
            string FileName = "test.txt";

            // Creates the file on server
            File.WriteAllLines(FilePath + FileName, asfinalLines);

            // Prompts user to save file
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + FileName);
            response.Flush();

            // Deletes the file on server
            File.Delete(FilePath + FileName);

            response.Close();

解决方案

Approach 1: Using a temporary file
If you just want to delete the file after the file transfer or perform some other clean up operations you may do this

// generate you file
// set FilePath and FileName variables
string stFile = FilePath + FileName;
try {
    response.Clear();
    response.ContentType = "text/plain";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
    response.TransmitFile(stFile);
    response.Flush();
} catch (Exception ex) {
    // any error handling mechanism
} finally {
    if (System.IO.File.Exists(stFile)) {
        System.IO.File.Delete(stFile);
    }
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

Approach 2: Without saving file to the server
If your text data is small then you may follow another (DO NOT use this approach for large data transfers), you can directly deliver the context as text file to the clients without saving them on to the server

try {
    // assuming asFinalLines is a string variable
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader("Content-Length", asFinalLines.Length.ToString());
    Response.ContentType = "text/plain";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
    Response.Write(asFinalLines);
    response.Flush();
} catch (Exception ex) {
    Debug.Print(asFinalLines);
} finally {
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

PS: I am a VB.NET person, tried to convert the code above in c# it may have some case-sensitivity issues but the logic is crystal clear

UPDATE:

Approach 3: Executing other code with file transfer.
It must be kept in mind that you can not have multiple responses to one request. You can NOT update your page and transmit a file in a single response. The headers can be set only once per request.

In this case you have to follow this methodology:

  • Create a new Div/Label where you will display a link to the file for download. Keep it hidden by default.
  • Process the request
  • Generate the required file (do NOT transmit yet, only save to server)
  • Perform other tasks, update your front end (i.e. refresh grid, display message etc) and also
  • Provide a link to the generated file in the hidden Label and show it. (You can also use your message div to provide the download link.
  • On download request from the link displayed in previous step transmit the file and then delete it as mentioned in Approach 1 (do NOT regenerate, only transmit/delete).
  • Alternatively you can delete old file before processing and generating new file. In this way you can allow the user to download the old file until a new file is generated. This method is better suitable for large files.

This approach adds an additional step for downloading the file after generating and does not support direct data transmission i.e. without saving it to the server.

这篇关于替代Response.TransmitFile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆