簡體   English   中英

使用AJAX調用在javascript中下載文件

[英]File Download in javascript using AJAX call

這是我的Java腳本代碼,用於在按鈕單擊時從數據庫下載文件,當按鈕單擊時此函數調用。 使用ajax調用我已經移到處理程序。

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) {
        }
    });
}

處理程序頁面到了,我已經將文件的字節保存byte [] buffer 這里的問題是下載無法正常工作。 由於Iam是初學者,所以我無法弄清楚問題所在。 請幫忙,謝謝。

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;
    }

這是很多次說過的話。 您不能通過Ajax調用來做到這一點。

您可以通過調用隱藏的iframe實現此目的,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM