gpt4 book ai didi

c# - Response.TransmitFile() 的替代品

转载 作者:行者123 更新时间:2023-11-30 12:24:41 27 4
gpt4 key购买 nike

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

响应.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:通过文件传输执行其他代码。
必须记住,您不能对一个请求有多个响应。您不能在一次响应中更新页面和传输文件。每个请求只能设置一次 header 。

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

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

这种方式在生成文件后增加了一个额外的下载步骤,不支持直接传输数据,即不保存到服务器。

关于c# - Response.TransmitFile() 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102546/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com