【问题标题】:Downloading pdf file with a name stored in database下载名称存储在数据库中的 pdf 文件
【发布时间】:2014-07-28 17:39:20
【问题描述】:

我正在尝试下载 pdf 文件,我正在使用 e.CommandArgument 传输文件,但我想为文件添加不同的标题,因为我的文件名附加了 GUID,因此 e.CommandArgument 也有 GUID 和因此,当下载文件时,它带有 GUID,我不希望下载文件上有 GUID。那么我的 Content-Disposition Header 应该发生什么变化?

我将不带 GUID 的文件名存储在列名为 RecieptFileName 的数据库中,所以如果有人能告诉我,我应该在我的代码中更改什么以下载只有文件名而没有附加 GUID 的文件。

这是我的 aspx 代码:

<asp:TemplateField HeaderText="Receipt" SortExpression="Receipt">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Bind("filename") %>' Text='<%# Bind("ReceiptFileName") %>' ></asp:LinkButton> //I want to download file with this LinkButton text i.e. ReceiptFileName
        </ItemTemplate>
</asp:TemplateField>

代码:

protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Download")
    {
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition", "attachment; Filename=" + e.CommandArgument + ".pdf");
        Response.TransmitFile(Server.MapPath("~/Match/Reciepts/") + e.CommandArgument);
        Response.End();
    }
} 

【问题讨论】:

  • 更改content-disposition 标头。
  • 是的,我知道我必须改变它,但你有什么建议我应该改变它吗?

标签: c# asp.net


【解决方案1】:

这里有多个选项。

选项 1:通过CommandArgument 传递多个值,以分隔字符分隔。

<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Eval("filename") + "," + Eval("ReceiptFileName")%>' Text='<%# Bind("ReceiptFileName") %>'></asp:LinkButton>

注意:使用Eval 进行绑定,因为使用Bind 发送多个auguments 总是得到第二个参数的值(不知道为什么)。

并在您的命令函数中使用Split 函数访问值。

protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Download")
    {
        string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
        string fileNameWithGUID = commandArgs[0];
        string fileNameWithoutGUID = commandArgs[1];

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition", "attachment; Filename=" + fileNameWithoutGUID + ".pdf");
        Response.TransmitFile(Server.MapPath("~/Match/Reciepts/") + fileNameWithGUID);
        Response.End();
    }
} 

选项 2:您可以直接访问 LinkButton1 文本属性,如下所示

protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Download")
    {
         GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
         string strFileName = ((LinkButton)row.FindControl("LinkButton1")).Text;
         ...
         ...
    }
} 

【讨论】:

  • 谢谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多