Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 在ASP.NET中使用Ajax和web服务从SQL Server数据库下载文件_Jquery_Asp.net_Ajax_Web Services - Fatal编程技术网

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

Jquery 在ASP.NET中使用Ajax和web服务从SQL Server数据库下载文件,jquery,asp.net,ajax,web-services,Jquery,Asp.net,Ajax,Web Services,我曾尝试使用Ajax和web服务从SQL Server数据库下载一个特定文件,但代码运行正常,仍然无法下载该文件 我的HTML 尝试以下代码片段 [ScriptMethod] [WebMethod] public void DownloadFile(int id) { byte[] bytes; var id =HTTPContext.Current.Request.Form["id"];//add this lin

我曾尝试使用Ajax和web服务从SQL Server数据库下载一个特定文件,但代码运行正常,仍然无法下载该文件

我的HTML


尝试以下代码片段

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

不可以。您不能使用ajax请求下载文件。为什么不能使用ajax请求下载文件。我收到错误“System.Data.dll中出现类型为'System.InvalidOperationException'的异常,但未在用户代码中处理”@HelloItsMe从数据库检索字节数组时出错代码已完成调试您的代码并让我知道该行的确切行号comment this line
//bytes=(byte[])sdr[“image”]和取消注释
var bytes=File.ReadAllBytes(@“C:\temp\a.png”)
c:\temp
中复制一个名为'a.png'@HelloItsMe的图像