Amir
Amir

Reputation: 69

File Download in javascript using AJAX call

This is my java script code for downloading the file from database on button click, when the button clicks this function calls. using ajax call i have moved to handler.

function DownloadDocument() {
    var CurrentUserEmpId = CurrentSelectedUser;
    Ext.Ajax.request({
        url: "UploadAttachment.ashx?mode=DownloadDocument&EmployeeId=" + CurrentUserEmpId,
        success: function (response) {
            var data = response.responseText;
        },
        failure: function (form, action) {
        }
    });
}

Here comes the handler page, I have got bytes of my file to byte[] buffer. The problem here is download not working. I could't figure out the problem, since Iam a beginner. Please help with this, Thankyou.

case "DownloadDocument":

            WebClient web = new WebClient();
            try
            {
                byte[] buffer;

                var query2 = @"select LLD_Decleration_doc from (select  instance, Employee_id, lld_Decleration_doc, ROW_NUMBER() OVER(PARTITION BY Employee_id ORDER BY Update_Date DESC) Latest from [EManager].[dbo].[tax_benefit_declaration]) a where latest = 1 And Employee_id = @EmployeeId";

                using (SqlConnection con = new SqlConnection(db.ConnectionString))
                using (SqlCommand cmd = new SqlCommand(query2, con))
                {
                    SqlParameter param = cmd.Parameters.Add("@EmployeeId", SqlDbType.Int);
                    param.Value = EmployeeId;
                    con.Open();

                    buffer = (byte[])cmd.ExecuteScalar();
                    con.Close();
                }

                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.ContentType = "APPLICATION/OCTET-STREAM";
                String Header = "Attachment; Filename=NewFile";
                response.AppendHeader("Content-Disposition", Header);
                context.Response.BinaryWrite(buffer);
                response.End();
            }
            catch { }
            break;
    }

Upvotes: 1

Views: 684

Answers (1)

Paweł Głowacz
Paweł Głowacz

Reputation: 3046

This is something that it was said many times. You cant do this with Ajax call.

You can achive this by invoke hidden iframe for example:

                var body = Ext.getBody();
                var comp = body.getById('hiddenform-iframe-download');
                if (!Ext.isEmpty(comp)) {
                    comp.remove();
                }
                body.createChild({
                    tag: 'iframe',
                    cls: 'x-hidden',
                    id: 'hiddenform-iframe-download',
                    name: 'iframe',
                    src: "yourContextToDownload?param1="+something
                });

Upvotes: 2

Related Questions