不能在响应中发送文件

本文关键字:文件 响应 不能 | 更新日期: 2023-09-27 18:18:24

我有一个在服务器上运行的代码集,它正确地生成一个zip文件并将其存储在服务器上。我将该文件位置作为物理路径。

我所做的尝试都不允许我使用响应到客户端来下载该文件。

尝试1:

System.IO.FileInfo fi = new System.IO.FileInfo(zipFilePath);
//setup HTML Download of provided Zip.
//application/zip
Response.ClearContent();
Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application / zip";
Response.AddHeader("Content-Disposition",
"attachment; filename='"" + System.IO.Path.GetFileName(zipFilePath) + "'";");
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.TransmitFile(zipFilePath);
Response.Flush();
Response.End();

没有结果。代码执行没有错误,但没有下载到客户端。

尝试2:

//Almost the same as attempt 1, but with WriteFile instead
Response.WriteFile(zipFilePath);

没有结果,与尝试1相同。

尝试3:

//Note: Same Header Section as Attempts 1 and 2
System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.FileStream(zipFilePath, System.IO.FileMode.Open));
int CHUNK = 1024;
List<byte> FileArray = new List<byte>();
while (reader.BaseStream.Position < reader.BaseStream.Length)
    FileArray.AddRange(reader.ReadBytes(CHUNK));
byte[] bArray = FileArray.ToArray();
reader.Close();
Response.OutputStream.Write(bArray, 0, bArray.Length);
Response.Flush();
Response.End();

没有结果,与以前的尝试相同

尝试4:

//Identical to Attempt 3, but using BinaryWrite
Response.BinaryWrite(bArray);

没有结果,与以前的尝试相同。

每一个这些代码块运行没有错误,但保存文件对话框从来没有出现。我什么也得不到。我无论如何也想不出我可能错过了什么。

  • 文件路径已被验证为正确
  • 代码在服务器上运行,而不是在客户端上,我不能使用'WebClient '。
如果有人有什么建议,我洗耳恭听。我不知道如何让这个文件下载到客户端。

不能在响应中发送文件

我测试了你的代码(尝试1),并得到它工作良好的测试文件。如果文件路径是错误的,你会得到一个System.IO.FileNotFoundException,所以这可能不是问题。

解决这个问题的几个方法:

  • 尝试检查网页,例如,通过右键单击Chrome,选择inspect。然后点击Network选项卡,刷新页(您应该在其中获取文件)。检查响应请求的标头是什么?
  • 尝试将content-type设置为application/octet-stream
  • 在Visual Studio中使用调试器并逐步通过。

这原来是一个Ajax相关的错误,导致UpdatePanels和POST响应之间的问题。

通过添加调用

修复了页面加载的问题
ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnGenerate);