问题描述
- asp.net 下载pdf ,下载后的大小与实际大小不一样
-
代码是这样子的,从数据库读取文件的长度没问题,但浏览器下载后总是不一样?请问会是什么原因?SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess); if (dr.Read()) { string filename = dc + " + " + dr["filename"].ToString(); int length = int.Parse(dr["leng"].ToString()); Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8)); Context.Response.AddHeader("Content-Transfer-Encoding", "binary"); //if (filename.EndsWith("pdf")) //{ // Context.Response.ContentType = "application/pdf"; //} //else // Context.Response.ContentType = "application/x-msdownload";//"application/octet-stream"application/x-msdownload; Context.Response.ContentType = "application/octet-stream"; int bufferSize = 1024000; int bytesRead; long readFrom = 0; do { byte[] bytes = new byte[bufferSize]; bytesRead = (int)dr.GetBytes(3, readFrom, bytes, 0, bufferSize); //Response.BinaryWrite(bytes); Response.OutputStream.Write(bytes, 0, bytesRead); Response.Flush(); readFrom += bufferSize; } while (bytesRead == bufferSize);
解决方案
加content-length响应头试试。。
Response.AddHeader("content-length",length.ToString());
时间: 2024-09-17 04:52:07