繁体   English   中英

在asp.net C#中下载任何类型的文件

[英]Download any kind of file in asp.net c#

我在单击按钮时使用此代码,从中可以下载具有特定名称的文件。

但是我想要,当用户上传文件时,其详细信息就像任何ID证明详细信息文件一样。

现在,要验证用户管理员是否想要查看其ID证明详细信息。 因此,他将下载用户已上传的文件,并将其保存在数据库中。

因此文件可以是任何类型或扩展名。

private void Button1_click(object sender, System.EventArgs e)
{
    string filename="C:\myuploads\invoice.pdf";
    Response.ContentType = "Application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment;" + filename +);
    Response.TransmitFile(Server.MapPath(filename));
    Response.End();
}

当用户上传文件时,您应该能够使用发布文件的ContentType属性。 假设您使用的文件上传控件如下:

<asp:FileUpload ID="uploadFile" runat="server" />

上传文件后,使用

string fileType = uploadFile.PostedFile.ContentType

稍后下载该值时, Reponse.ContentType值保存在数据库中,并用作现有代码中Reponse.ContentType的值。

我想这就是你所追求的。

private void DownloadFile(string file)
{
    var fi = new FileInfo(file);
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", "attachment; filename="+ fi.Name);
    Response.WriteFile(file);
    Response.End();
}

因此,您可以这样称呼它:

string myfile = @"c:\path\To\Files\myFile.pdf"; //this wouldn't be a static string in your code
DownloadFile(myfile);

谢谢回答我的问题。 我的LinkBut​​ton可以从特定用户ID的数据库中下载文件,成功运行。

实际上,我的下载链接位于更新面板中,因此它需要“触发器”。而且我的链接位于GridView中,因此我已在触发器中传递了链接按钮ID。

每当我们在更新面板中使用GridView时,都有一个LinkBut​​ton可以从特定用户ID的数据库中下载文件。 我们应该在模板字段中传递** GridView ID而不是LinkBut​​ton ID。**

 <asp:UpdatePanel ID="upd" runat="server">
        <ContentTemplate>
    <asp:GridView ID="grd_UserList" runat="server" CssClass="table"
      DataKeyNames="Uid" AutoGenerateColumns="false" AllowPaging="false">
    <asp:TemplateField HeaderText="Task Name">
          <ItemTemplate>
    <asp:LinkButton Id="LinkDownload" runat="Server" CommandArgument='<%# Eval("Attachment") %>' >
          </ItemTemplate>
      </asp:TemplateField>

      </asp:GridView>
     </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="grd_UserList" />
        </Triggers>
    </asp:UpdatePanel>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM