简体   繁体   中英

How to call a function in ajax from web service that contains pdf attachment?

In my web services i can able to download the file , but i don,t know how to call this function in ajax.

I have datatable that contains button column, i want to achieve if i click the button in datatable , i want to download a pdf file from sql server database

please refer below my web service [WebMethod] public void DownloadFile(string id) {

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

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

            con.Open();

            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                sdr.Read();
                bytes = (byte[])sdr["Attachment"];
                // var bytes = File.ReadAllBytes(@"C:\temp\a.png");
                contentType = sdr["SalesNumber"].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 = @"application/pdf";// "image/png";


        //HttpContext.Current.Response.BinaryWrite(Buffer);

        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=" + contentType +".pdf");
        HttpContext.Current.Response.End();
        HttpContext.Current.Response.Flush();


    }

my ajax function for each row button:-

$('#datat tbody').on('click', 'button', function () {

                      var currow = $(this).closest('tr');
                      var col1 = currow.find('td:eq(1)').text();


                      $.ajax({
                          url: 'WebService1.asmx/DownloadFile',
                          data: JSON.stringify({ id: col1}),
                          method: 'post',
                          contentType: 'application/json;charset=utf-8',
                          dataType: 'json',
                          success: function (data) {
                              alert('PDF generated successfully.');
                          }
                      });

Please advise me a solution ... thanks for your help

I don't know if this is all you need, or if it will work from a web service, but i think you need at least

// note the quotes around the file name.
Response.AppendHeader("Content-Disposition", 
    "attachment; filename=\"" + fileName + "\"");

and

Response.TransmitFile(Server.MapPath("~/pathToYourFiles/" + fileName));

I do this without an output stream, i just configure the response (most of what you already have) and TransmitFile, so this might not work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM