使用ASP.NET中的Ajax和Web服务从SQL Server数据库下载文件

时间:2018-01-02 06:11:06

标签: jquery asp.net ajax web-services

我尝试使用Ajax和Web服务从SQL Server数据库下载特定文件,代码正常运行但仍无法下载文件。这是代码

我的HTML



<input id="btn_download" type="button" value="download_att" />
&#13;
&#13;
&#13; 我的ajax函数读取文件的id为retrive
&#13;
&#13;
$('#btn_download').click(function () {
                id = $('#Tid').val();
                $.ajax({
                    url: 'WebService1.asmx/DownloadFile',
                    method: 'POST',
                    contentType: 'application/json;charset=utf-8',
                    data: '{id:' + JSON.stringify(id) + '}',
                    success: function () {
                        alert("s");
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我的网络服务

[ScriptMethod]
[WebMethod]
public void DownloadFile(table id )
{
    byte[] bytes;

    string fileName, contentType;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TesterConnectionString1"].ConnectionString);

    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.CommandText = "select id,image from attach where id=@Id";
        cmd.Parameters.AddWithValue("@Id", id.id);
        cmd.Connection = con;

        con.Open();

        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            sdr.Read();
            bytes = (byte[])sdr["image"];
            contentType = sdr["id"].ToString();
            fileName = sdr["id"].ToString();
        }

        con.Close();
    }


    httpContext.Current.Response.Clear();
    httpContext.Current.Response.Buffer = true;
    httpContext.Current.Response.Charset = "";
    httpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    httpContext.Current.Response.ContentType = contentType;
    httpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    httpContext.Current.Response.BinaryWrite(bytes);
    httpContext.Current.Response.Flush();
    httpContext.Current.Response.End();
}

1 个答案:

答案 0 :(得分:0)

尝试以下代码段。

  [ScriptMethod]
        [WebMethod]
        public void DownloadFile(int id)
        {

            byte[] bytes;
var id =HTTPContext.Current.Request.Form["id"];//add this line to ref to id
            string fileName, contentType;
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TesterConnectionString1"].ConnectionString);

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select image from test where Id=@Id";
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Connection = con;

                con.Open();

                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["image"];
                    // var bytes = File.ReadAllBytes(@"C:\temp\a.png");
                    contentType = sdr["id"].ToString();
                    fileName = sdr["filename"].ToString();
                }

                con.Close();
            }
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.ContentType = contentType;// "image/png";
            HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
            HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();


        }

<强>的javascript

 $(document).ready(function () {
            function downloadUrl(url) {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.responseType = 'arraybuffer';
                xhr.onload = function () {
                    if (this.status === 200) {
                        var filename = "";
                        var disposition = xhr.getResponseHeader('Content-Disposition');
                        if (disposition && disposition.indexOf('attachment') !== -1) {
                            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                            var matches = filenameRegex.exec(disposition);
                            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                        }
                        var type = xhr.getResponseHeader('Content-Type');

                        var blob = typeof File === 'function'
                            ? new File([this.response], filename, { type: type })
                            : new Blob([this.response], { type: type });
                        if (typeof window.navigator.msSaveBlob !== 'undefined') {
                            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                            window.navigator.msSaveBlob(blob, filename);
                        } else {
                            var URL = window.URL || window.webkitURL;
                            var downloadUrl = URL.createObjectURL(blob);

                            if (filename) {
                                // use HTML5 a[download] attribute to specify filename
                                var a = document.createElement("a");
                                // safari doesn't support this yet
                                if (typeof a.download === 'undefined') {
                                    window.location = downloadUrl;
                                } else {
                                    a.href = downloadUrl;
                                    a.download = filename;
                                    document.body.appendChild(a);
                                    a.click();
                                }
                            } else {
                                window.location = downloadUrl;
                            }

                            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                        }
                    }
                };
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                var params = {};
                params.id = $('#YOUR ID');//add this line to send id 
                xhr.send($.param(params));
            }

            $("#btn").click(function () {
                downloadUrl("/WebService1.asmx/DownloadFile")
            });
        })