【问题标题】:File does not download in ASP.NET文件无法在 ASP.NET 中下载
【发布时间】:2017-07-01 05:58:02
【问题描述】:

我正在尝试在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 的代码有何关联。
  • 您应该将代码更改为重定向到专用处理程序,该处理程序将为文件提供服务,而不是直接从回发事件处理程序执行。

标签: asp.net .net-3.5


【解决方案1】:

您正在使用更新面板,那么您需要添加触发器。

<asp:PostBackTrigger ControlID="YourControlID" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    相关资源
    最近更新 更多