jQuery和ASP.NET从数据库下载文件

时间:2013-02-14 20:27:03

标签: c# jquery asp.net webforms

我查看了许多在线资源并构建了我的脚本,但它似乎仍然没有给我这个文件。它只是加载页面“client-home2.aspx / downloadAttachment”而不是执行代码并传递文件。

这是我背后的代码:

    [WebMethod]
    public void downloadAttachment(string id)
    {

        DbProviderFactory dbf = DbProviderFactories.GetFactory();
        using (IDbConnection con = dbf.CreateConnection())
        {
            string sSQL;
            sSQL = "select top 1                " + ControlChars.CrLf
                 + " FILENAME, FILE_MIME_TYPE, ATTACHMENT" + ControlChars.CrLf
                 + "  from vwATTACHMENTS_CONTENT" + ControlChars.CrLf
                 + " where 1 = 1                    " + ControlChars.CrLf;
            //Debug.Print(sSQL);
            using (IDbCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = sSQL;

                Sql.AppendParameter(cmd, id.ToString(), "ATTACHMENT_ID");

                cmd.CommandText += " order by DATE_ENTERED desc" + ControlChars.CrLf;

                using (DbDataAdapter da = dbf.CreateDataAdapter())
                {
                    ((IDbDataAdapter)da).SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        da.Fill(dt);

                        if (dt.Rows.Count > 0)
                        {

                            foreach (DataRow r in dt.Rows)
                            {
                                string name = (string)r["FILENAME"];
                                string contentType = (string)r["FILE_MIME_TYPE"];
                                Byte[] data = (Byte[])r["ATTACHMENT"];

                                // Send the file to the browser
                                Response.AddHeader("Content-type", contentType);
                                Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
                                Response.BinaryWrite(data);
                                Response.Flush();
                                Response.End();
                            }

                        }
                        else
                        {

                        }
                    }
                }
            }

        }

    }

这是我的jQuery:

$('.attachmentLink').click(function () {
    var id = $(this).attr('id');
    /*
    $.ajax({
    type: "POST",
    url: "client-home2.aspx/downloadAttachment",
    data: '{id:\'' + id + '\'}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
    //alert(msg.d);
    }
    });
    */
    $.download('client-home2.aspx/downloadAttachment', 'id=' + id);
    return false;
});

我正在使用此功能http://filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/

问题是,它永远不会给我文件;它只是导航到client-home2.aspx/downloadAttachment

如何解决此问题以便我可以下载文件?

谢谢。

3 个答案:

答案 0 :(得分:2)

每个WebMethod调用只能发送一个HTTP响应。这意味着一次只能有一个文件。使用Response.End()阻止其他任何东西返回到Web浏览器,并且第二次通过foreach循环可能会抛出异常。解决这个问题的唯一方法是从你的jQuery代码中调用WebMethod 20次,并且如果查询中有多个结果,则每次都要知道要返回哪个文件。即使这可能也行不通。

但我怀疑你真的打算让ID字段只产生一条记录。在这种情况下,您需要了解两件事。第一个是当您更改CommandText属性时,SqlCommand类型会重置它的Parameters集合。因此,您需要在添加ID参数之前完成创建整个sql字符串文本。第二个是你的ID参数现在甚至都不重要,因为你的sql代码从不引用那个参数

我对发布这段代码犹豫不决,因为还有其他一些东西也可能出错,但这应该是对你所拥有的东西的改进。请注意,我最终也做了同样的工作,但是少了很少的代码

[WebMethod]
public void downloadAttachment(string id)
{

    string SQL =
          "select top 1 FILENAME, FILE_MIME_TYPE, ATTACHMENT" + ControlChars.CrLf
        + "  FROM vwATTACHMENTS_CONTENT" + ControlChars.CrLf
        + " where ID = @ATTACHMENT_ID" + ControlChars.CrLf
        + " order by DATE_ENTERED desc";
    //Debug.Print(SQL);

    DbProviderFactory dbf = DbProviderFactories.GetFactory();
    using (IDbConnection con = dbf.CreateConnection())
    using (IDbCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = SQL;
        Sql.AppendParameter(cmd, id, "ATTACHMENT_ID");

        using (IDataReader rdr = cmd.ExecuteReader())
        {
            if (rdr.Read())
            {
                // Send the file to the browser
                Response.AddHeader("Content-type", r["FILE_MIME_TYPE"].ToString());
                Response.AddHeader("Content-Disposition", "attachment; filename=" + r["FILENAME"].ToString());

                Response.BinaryWrite((Byte[])r["ATTACHMENT"]);

                Response.Flush();
                Context.ApplicationInstance.CompleteRequest();
            }
        }
    }
}

答案 1 :(得分:0)

以下是我过去的做法,但我的方式不同:

查看:

foreach (var file in foo.Uploads)
  {
      <tr>
        <td>@Html.ActionLink(file.Filename ?? "(no filename)", "Download", "Upload", new { id = file.UploadId }, null)</td>
      </tr>
  }

我的UploadConroller中的代码:

public ActionResult Download(Guid id)
{
    var upload = this.GetUpload(id);
    if (upload == null)
    {
        return NotFound();
    }

    return File(upload.Data, upload.ContentType, upload.Filename);
}


private Upload GetUpload(Guid id)
{
    return (from u in this.DB.Uploads
            where u.UploadId == id
            select u).SingleOrDefault();
}

随意对货物进行崇拜,这非常简单。

答案 2 :(得分:0)

我明白了。我必须创建一个单独的文件,因为标题已经被发送。因此,我的单独文件名为“downloadAttachment”,如下所示:

using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Web.Services;
using System.Text;
using System.Web.Script.Services;
using System.Text.RegularExpressions;
using System.IO;

namespace SplendidCRM.WebForms
{
    public partial class downloadAttachment : System.Web.UI.Page
    {
        string HostedSite;
        protected DataView vwMain;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Sql.IsEmptyGuid(Security.USER_ID))
                Response.Redirect("~/Webforms/client-login.aspx");

            HostedSite = Sql.ToString(HttpContext.Current.Application["Config.hostedsite"]);

            string id = Request.QueryString["ID"].ToString();

            DbProviderFactory dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                string sSQL;
                sSQL = "select top 1                " + ControlChars.CrLf
                     + " FILENAME, FILE_MIME_TYPE, ATTACHMENT" + ControlChars.CrLf
                     + "  from vwATTACHMENTS_CONTENT" + ControlChars.CrLf
                     + " where 1 = 1                    " + ControlChars.CrLf;
                //Debug.Print(sSQL);
                using (IDbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sSQL;

                    Sql.AppendParameter(cmd, id.ToString(), "ATTACHMENT_ID");

                    cmd.CommandText += " order by DATE_ENTERED desc" + ControlChars.CrLf;

                    using (DbDataAdapter da = dbf.CreateDataAdapter())
                    {
                        ((IDbDataAdapter)da).SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            da.Fill(dt);

                            if (dt.Rows.Count > 0)
                            {

                                foreach (DataRow r in dt.Rows)
                                {
                                    string name = (string)r["FILENAME"];
                                    string contentType = (string)r["FILE_MIME_TYPE"];
                                    Byte[] data = (Byte[])r["ATTACHMENT"];

                                    // Send the file to the browser
                                    Response.AddHeader("Content-type", contentType);
                                    Response.AddHeader("Content-Disposition", "attachment; filename=" + MakeValidFileName(name));
                                    Response.BinaryWrite(data);
                                    Response.Flush();
                                    Response.End();
                                }

                            }
                            else
                            {

                            }
                        }
                    }
                }

            }

        }

        public static string MakeValidFileName(string name)
        {
            string invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
            string invalidReStr = string.Format(@"[{0}]+", invalidChars);
            string replace = Regex.Replace(name, invalidReStr, "_").Replace(";", "").Replace(",", "");
            return replace;
        }

    }
}