使用IIS和C# HttpWebRequest下载XLSX/DOCX文件损坏问题
问题分析与解决方案
你的Office文件(XLSX/DOCX)下载损坏,核心原因是响应流混入额外内容以及文件名参数错误,PDF因格式容错性强未受影响。以下是具体修复方案:
关键修复点
- 修正文件名配置:
Content-Disposition中的filename需用纯文件名而非完整路径,否则会导致文件解析异常。 - 重置响应流:清空页面原有输出(如HTML代码),避免破坏二进制文件结构。
- 终止后续输出:下载完成后立即终止响应,防止多余内容写入文件流。
- 优化流读取逻辑:复用缓冲区,减少不必要的内存分配。
修复后的完整代码
protected void btnActionDocAnsehen_Click(object sender, CommandEventArgs e) { // 原代码中未使用的SqlConnection建议移除,避免资源泄漏 // string connectionString = ConfigurationManager.ConnectionStrings["dataConnection"].ToString(); // SqlConnection conn = new SqlConnection(connectionString); // conn.Open(); string filepath = pfad; Stream stream = null; int bytesToRead = 10240; // 使用10KB标准缓冲区 byte[] buffer = new Byte[bytesToRead]; try { HttpWebRequest httpCopyRequest = (HttpWebRequest)WebRequest.Create(filepath); httpCopyRequest.Timeout = 3000; httpCopyRequest.PreAuthenticate = true; using (HttpWebResponse httpCopyResponse = (HttpWebResponse)httpCopyRequest.GetResponse()) { stream = httpCopyResponse.GetResponseStream(); var resp = HttpContext.Current.Response; // 清空原有响应内容,重置状态 resp.Clear(); resp.Buffer = true; // 设置正确的MIME类型 resp.ContentType = ReturnFiletype(Path.GetExtension(filepath)); // 使用纯文件名,避免路径干扰 string fileName = Path.GetFileName(filepath); resp.AddHeader("Content-Disposition", $"attachment; filename=\"{fileName}\""); // 可选:设置文件大小,帮助浏览器识别 resp.AddHeader("Content-Length", httpCopyResponse.ContentLength.ToString()); int length; while (resp.IsClientConnected && (length = stream.Read(buffer, 0, bytesToRead)) > 0) { resp.OutputStream.Write(buffer, 0, length); resp.Flush(); } } } catch (WebException ex) { string message = "Die Datei konnte auf dem Server nicht gefunden werden! Bitte kontaktieren Sie die Administration!"; ClientScript.RegisterStartupScript(GetType(), "alert", $"alert('{message}');", true); } finally { stream?.Close(); // 终止响应,防止后续内容混入下载文件 HttpContext.Current.Response.End(); } }
额外注意事项
- 确保
ReturnFiletype返回正确的MIME类型:- XLSX:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - DOCX:
application/vnd.openxmlformats-officedocument.wordprocessingml.document - 不确定类型时可直接使用
application/octet-stream
- XLSX:
内容的提问来源于stack exchange,提问作者David Loraj
相关产品推荐
相关产品推荐

