所以我有了过去几天一直在摆弄的代码集,我需要从服务器下载一个文件到客户端。这是很简单的部分,但我还需要在完成后刷新网格视图,并在警告中显示文件已成功创建,但我找到的每一种下载方式都包含一行选定的代码,这将是我的失败。
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();发布于 2015-10-14 21:42:53
方法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:通过文件传输执行其他代码。
必须记住,您不能对一个请求有多个响应。您不能在单个响应中更新页面和传输文件。每个请求只能设置一次标头。
在这种情况下,您必须遵循以下方法:
这种方法增加了在生成文件后下载文件的附加步骤,并且不支持直接数据传输,即不将其保存到服务器。
https://stackoverflow.com/questions/33102546
复制相似问题