gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:17:37 26 4
gpt4 key购买 nike

我尝试使用 Ajax 和 Web 服务从 SQL Server 数据库下载特定文件,代码工作正常,没有错误,但仍然无法下载该文件。以下是代码

我的 HTML

<input id="btn_download" type="button" value="download_att" />
我的ajax函数读取文件检索的id
$('#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);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我的网络服务

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

最佳答案

尝试以下代码片段。

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

关于jquery - 使用 Ajax 和 ASP.NET 中的 Web 服务从 SQL Server 数据库下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48056306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com