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

本文关键字:数据库 下载 文件 NET ASP jQuery | 更新日期: 2023-09-27 17:59:08

我查看了许多在线资源,并构建了我的脚本,但它似乎仍然没有给我文件。它只是加载页面"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/

问题是,它从来没有给我文件;它只是导航到CCD_ 1。

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

谢谢。

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

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

以下是我过去的做法,但我的做法有所不同:

视图:

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

请随意货运邪教,这很简单。

我想明白了。我不得不制作一个单独的文件,因为邮件头已经在发送了。因此,我的单独文件被称为"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;
        }
    }
}