2

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

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

谢谢你。

4

3 回答 3

2

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

但我怀疑你真的打算让那个 ID 字段只产生一条记录。在这种情况下,您需要注意两件事。第一个是 SqlCommand 类型在您更改CommandText属性时重置它的参数集合。因此,您需要在添加 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();
            }
        }
    }
}
于 2013-02-14T20:33:11.503 回答
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();
}

随意运送邪教,这很简单。

于 2013-02-14T20:37:35.107 回答
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;
        }

    }
}
于 2013-02-14T21:54:34.680 回答