I've tried to download a specific file from a SQL Server database using Ajax and a web service and a code is working without errors and still can't download the file.Here is the code
What I have tried:
My HTML
<pre><input id="btn_download" type="button" value="download_att" />
my ajax function to read id for file retrive
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre lang="Javascript"><pre lang="Javascript">$('#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);
}
});
});
my webservice
[ScriptMethod]
[WebMethod]
public void DownloadFile(int id )
{
byte[] bytes;
string fileName, contentType;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TesterConnectionString1"].ConnectionString);
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select image from attach where Id=@Id";
cmd.Parameters.AddWithValue("@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();
}