Response.TransmitFile()的替代方案

所以我有一套我过去几天一直在玩的代码,我需要从服务器下载一个文件到客户端。 这是一个简单的部分,但我还需要在完成后刷新网格视图并在警报中显示文件已成功创建,但我发现下载的每一种方式都包含一行代码,这将是我的倒台。

到Response.End()

Response.Close()或

ApplicationInstance.CompleteRequest()

所有这些都结束了当前的响应,或者我相信在ApplicationInstance的情况下,它将页面的所有源代码刷新到我试图下载的文本文件中。 下面是我从服务器下载文件的代码片段,以下是下载文件的源代码。 如果你有任何可以帮助解决这个永无止境的噩梦,那将非常感激。

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

方法1: 使用临时文件
如果您只想在文件传输后删除文件或执行其他一些清理操作,您可以执行此操作

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

方法2: 不将文件保存到服务器
如果你的文本数据很小,那么你可以跟随另一个(不要使用这种方法进行大数据传输),你可以直接将上下文作为文本文件传递给客户端而不将它们保存到服务器上

 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:我是VB.NET的人,试图在c#中转换上面的代码,它可能有一些区分大小写的问题,但逻辑很明确

更新:

方法3: 使用文件传输执行其他代码。
必须记住,您不能对一个请求进行多次回复。 您无法在单个响应中更新页面并传输文件。 每个请求只能设置一次标头。

在这种情况下,您必须遵循以下方法:

  • 创建一个新的Div / Label ,您将在其中显示要下载的文件的链接。 默认情况下保持隐藏状态
  • 处理请求
  • 生成所需文件( 不要传输 ,只保存到服务器)
  • 执行其他任务,更新前端(即刷新网格,显示消息等)以及
  • 在隐藏标签中提供指向生成文件的链接并显示它。 (您也可以使用消息div来提供下载链接。
  • 在上一步显示的链接的下载请求中,发送文件,然后按方法1中所述删除它( 不重新生成 ,仅发送/删除)。
  • 或者,您可以在处理和生成新文件之前删除旧文件。 通过这种方式,您可以允许用户下载旧文件,直到生成新文件。 此方法更适合大文件。

此方法在生成后添加了下载文件的附加步骤,并且不支持直接数据传输,即不将其保存到服务器。