SQL Server データベースにバイナリとして保存された多数のファイルがあります。これらのファイルをユーザーに配信する .ashx ファイルを作成しました。残念ながら、ファイルがかなり大きくなると、次のエラーで失敗します。
算術演算のオーバーフローまたはアンダーフロー
バイナリをバイト[]にロードすると、メモリが不足すると思います。
それで、私の質問は、データベーステーブルからのものである場合、どうすればこの機能をチャンクで読み込むことができますか? Response.TransmitFile() も良いオプションのようですが、これはデータベースでどのように機能しますか?
以下のコードの DB.GetReposFile() は、データベースからファイルを取得します。エントリには、Filename、ContentType、datestamps、および varbinary としての FileContent など、さまざまなフィールドがあります。
これは、ファイルを配信するための私の機能です。
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>");
}
更新: 私が最終的に得た機能は、以下にリストされているものです。DB.GetReposFileSize() は、Tim が言及しているように、コンテンツの Datalength を取得するだけです。元のコードでは、次の 2 行の代わりにこの関数を呼び出します。
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);
}
}