我们有很多文件,在我们的 SQL Server 数据库中保存为二进制文件。我制作了一个 .ashx 文件,将这些文件传递给用户。不幸的是,当文件变得相当大时,它会失败,并出现以下错误:
算术运算中的上溢或下溢
我假设它内存不足,因为我将二进制文件加载到字节 [] 中。
所以,我的问题是,当它来自数据库表时,我怎样才能制作这个功能,分块读取(也许?)?似乎 Response.TransmitFile() 也是一个不错的选择,但同样,这将如何与数据库一起使用?
下面代码中的 DB.GetReposFile() 从数据库中获取文件。条目有多个字段:文件名、内容类型、日期戳和作为 varbinary 的文件内容。
这是我的功能,交付文件:
context.Response.Clear();
try
{
if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
{
int id = Int32.Parse(context.Request.QueryString["id"]);
DataTable dtbl = DB.GetReposFile(id);
string FileName = dtbl.Rows[0]["FileName"].ToString();
string Extension = FileName.Substring(FileName.LastIndexOf('.')).ToLower();
context.Response.ContentType = ReturnExtension(Extension);
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
byte[] buffer = (byte[])dtbl.Rows[0]["FileContent"];
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Need a valid id</p>");
}
}
catch (Exception ex)
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>" + ex.ToString() + "</p>");
}
更新: 我最终得到的功能是下面列出的功能。正如 Tim 所提到的,DB.GetReposFileSize() 只是获取内容 Datalength。我在原始代码中调用了这个函数,而不是这两行:
byte[] buffer = (byte[])dtbl.Rows[0]["FileContent"];
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
新的下载功能:
private void GetFileInChunks(HttpContext context, int ID)
{
//string path = @"c:\somefile.txt";
//FileInfo file = new FileInfo(path);
int len = DB.GetReposFileSize(ID);
context.Response.AppendHeader("content-length", len.ToString());
context.Response.Buffer = false;
//Stream outStream = (Stream)context.Response.OutputStream;
SqlConnection conn = null;
string strSQL = "select FileContent from LM_FileUploads where ID=@ID";
try
{
DB.OpenDB(ref conn, DB.DatabaseConnection.PDM);
SqlCommand cmd = new SqlCommand(strSQL, conn);
cmd.Parameters.AddWithValue("@ID", ID);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
reader.Read();
byte[] buffer = new byte[1024];
int bytes;
long offset = 0;
while ((bytes = (int)reader.GetBytes(0, offset, buffer, 0, buffer.Length)) > 0)
{
// TODO: do something with `bytes` bytes from `buffer`
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
offset += bytes;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
DB.CloseDB(ref conn);
}
}