1
ASP.NET
ウェブサイトにダウンロードファイルの機能を追加しようとしています。以下は、データを保持するクラスです:ASP.NETでファイルがダウンロードされない
public class L_Attachment
{
public Int32 ParentId;
public L_AttachmentTypes Type;
public String FileName;
public String FileExtension;
public Byte[] FileData;
public enum L_AttachmentTypes
{
CONTRACT = 1,
RECEIVE = 2
}
}
FileData
フィールドは、ファイルを構築するためにbytes
を保持しています。以下は、ファイルをダウンロードするための私のコードです。
protected void gvAttachmentList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadAttachment")
{
Int32 index = Convert.ToInt32(e.CommandArgument);
Int32 id = Convert.ToInt32(this.gvAttachmentList.DataKeys[index].Value);
L_Attachment attachment = L_Attachment.GetById(id);
try
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + attachment.FileName + attachment.FileExtension + "\"");
Response.AddHeader("Content-Length", attachment.FileData.Length.ToString());
Response.BufferOutput = false;
Response.OutputStream.Write(attachment.FileData, 0, attachment.FileData.Length);
Response.Flush();
}
catch (Exception ex)
{
Message msg = new Message();
msg.Type = MessageType.Error;
msg.Msg = "Error occurred. Details: " + ex.Message;
ShowUIMessage(msg);
}
}
しかし、ユーザーが終了しても、ユーザーがウェブページの[ダウンロード]ボタンを押しても何も起こりません。ファイルはクライアントPCに保存する必要があります。
上記のコードで何が間違っているのか調べてください。
"ダウンロードボタン"があなたの 'Response.OutputStream.Write'を呼び出すコードにどのように関係しているか説明していません。 – Dai
コードをPostbackイベントハンドラから直接行うのではなく、ファイルを提供する専用のハンドラへのリダイレクトに変更する必要があります。 – Dai