Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
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

HTML
[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();
}
Posted
Comments
Karthik_Mahalingam 3-Jan-18 1:46am    
I dont think this method will work. create a page and load it inside iframe to download which will be very simple and easier.
HelloIt'sMe_M 3-Jan-18 2:03am    
why not work?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900