如何使用c#在asp.net中下载文件

时间:2016-03-22 11:24:33

标签: c# asp.net

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

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

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)以便在我想创建按钮下载文件时使用它?

我在数据列表中添加了一个链接按钮,并添加了命令name = Download

和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();
        }
    }

但它仍然无效?

谢谢

2 个答案:

答案 0 :(得分:1)

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")        
      }

    }

答案 1 :(得分:0)

这可能超出了你所寻找的范围,但我通常用脚本来做这件事。

创建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);
   }