繁体   English   中英

如何使用C#在ASP.NET中下载文件

[英]How to download a file in asp.net using c#

我有一个网页,用于基于(查询字符串)显示有关文件的文件信息(例如名称和图片)((文件已经保存在服务器上))

这些文件的详细信息将显示在(数据列表)中。单击该文件时如何创建命令按钮以下载文件

void FillLessons()
{
    SqlConnection cn = new SqlConnection(cs);
    cn.Open();
    SqlCommand cmd = new SqlCommand();


    string sqlStatment = "SELECT Lesson_Id,Lesson_Title,Subject_Id,Lesson_Img FROM [Ali].[dbo].[tblLessons] where Subject_Id ='" + Request.QueryString["id"].ToString() + "' ";

    cmd.CommandType = CommandType.Text;
    cmd.CommandText = sqlStatment;
    cmd.Connection = cn;

    DataTable dt = new DataTable();

    dt.Load(cmd.ExecuteReader());

    dllessons.DataSource = dt;
    dllessons.DataBind();
}

当我要创建一个下载文件的按钮时,我不知道如何从数据表(dt)中提取文件名(Lesson_Title)来使用它?

我在数据列表中添加了链接按钮,并添加了命令名称=下载

和CommandArgument ='<%#Eval(“ Lesson_Title”)%>'

比键入此代码

   protected void dllessons_ItemCommand(object sender, DataListCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            Response.Clear();
            Response.ContentType = "application/octect-stream";
            Response.AppendHeader("content-disposistion", "filename=" + e.CommandArgument);
            Response.TransmitFile (Server.MapPath("~/My_Lessons/") + e.CommandArgument);
            Response.End();
        }
    }

但它仍然无法正常工作??

谢谢

ASPX;

 <asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="downloadButton" runat="server" 
          CommandName="DownloadFile" 
    CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
          Text="Download File" />
      </ItemTemplate> 
    </asp:TemplateField>

后面的代码;

    protected void GridView1_RowCommand(object sender, 
      GridViewCommandEventArgs e)
    {
      if (e.CommandName == "DownloadFile")
      {
        int index = Convert.ToInt32(e.CommandArgument);    
        GridViewRow row = GridView1.Rows[index];
        //Label or HiddenField for getting file url
        Label lblFileUrl = (Label)row.FindControl("YourFileUrlControlId")        
      }

    }

这可能超出了您要查找的范围,但是我通常使用脚本进行此操作。

创建一个iframe:

downloadFile: function (versionId) {
    var id = versionId;

    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = "/File/DownloadFile/?fileId=" + id;
},

服务器代码:

  public ActionResult DownloadFile(Guid fileId)
   {
      var file = _FileService.GetFileData(fileId);

      return File(file.Stream, file.ContentType, file.Name);
   }

暂无
暂无

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

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