使用存储在数据库中的名称下载pdf文件

时间:2014-07-28 17:39:21

标签: c# asp.net

我正在尝试下载pdf文件,我正在使用e.CommandArgument来传输文件,但我想在文件中添加不同的标题,因为我的文件名附加了GUID,因此e.CommandArgument也是有一个GUID,因此当下载文件时它带有GUID,我不希望GUID下载的文件。那么我的内容配置标题应该改变什么呢?

我在没有GUID的情况下将文件名存储在数据库中,列名为RecieptFileName,所以如果有人可以告诉我应该在我的代码中更改哪些文件只下载文件名并且没有附加GUID。< / p>

这是我的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();
    }
} 

1 个答案:

答案 0 :(得分:0)

这里有多个选项。

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

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

注意:使用Eval进行绑定,因为使用Bind发送多个增量值总是会得到第二个参数的值(不确定原因)。

在命令函数中使用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;
         ...
         ...
    }
} 
相关问题