2017-02-13 7 views
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に保存する必要があります。

上記のコードで何が間違っているのか調べてください。

+0

"ダウンロードボタン"があなたの 'Response.OutputStream.Write'を呼び出すコードにどのように関係しているか説明していません。 – Dai

+0

コードをPostbackイベントハンドラから直接行うのではなく、ファイルを提供する専用のハンドラへのリダイレクトに変更する必要があります。 – Dai

答えて

2

更新パネルを使用しているため、トリガーを追加する必要があります。

<asp:PostBackTrigger ControlID="YourControlID" /> 
+0

ありがとうございます...問題を解決しました... –

関連する問題