Как скачать файл Excel с помощью метода Ajax - здесь мой файл загружается в папку Temp, а не загружается в браузере? - PullRequest
0 голосов
/ 19 января 2019

Я хочу скачать файл Excel. Я использую метод ajax, чтобы получить файл, но он не работает для меня. Мой файл загружен во временную папку, но не загружается в браузер.

c # и jquery

JQuery

//Exporting errors to excel file
function ExcportErrorListToExcel() {
    debugger;
    $.ajax({
        url: 'Import/ExportErrorToExcel',
        type: 'GET',
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        //contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        success: function (returnValue) {
            debugger;       
            window.location = '/Import/ExportErrorToExcel?file=' + returnValue.filename;
            //alert('success');
        }
    });
}

Контроллер

#region ExportErrorToExcel        
        public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
        {
            UA patsUA = Session["PaTSUA"] as UA;
            DataTable dataTable = null;
            dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);

            string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xlsx");


          _dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);

            FileInfo fileInfo = new FileInfo(tempPath);
            if (fileInfo.Exists)
            {
                Response.Clear();
                byte[] excelBytes = System.IO.File.ReadAllBytes(tempPath);

                MemoryStream memoryStream = new MemoryStream(excelBytes);
                Response.ContentType= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=ErrorList.xlsx");
                Response.Buffer = true;
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
                //System.IO.File.Delete(tempPath);
            }

            //var errorRowList = (from e in dataTable.AsEnumerable()
            //                             where e.Field<string>("DataError").ToString() != ""
            //                             select e).ToList();

            return File(tempPath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(tempPath));
            //return Json(new { Status = "OK", Records = tempPath, contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        }
        #endregion ExportErrorToExcel

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

Это можно сделать, просто разделив эту функцию контроллера на две. Первая функция сохранит файл во временной папке и передаст имя файла функции jjery Ajax, а в разделе об успешном выполнении она будет перенаправлена ​​ко второй функции вКонтроллер. Здесь мы скачаем файл

Вот Ajax

    function ExportErrorListToExcel() {
    debugger;
    $.ajax({
        url: "Import/ExportErrorToExcel",
        type: "POST",
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        success: function (responsetext, status, xhr) {
            debugger;
            window.location = 'Import/DownloadErrorData?fname=' + responsetext.FileName;
        }
    });
   // $('#ExcelExportForm').submit();
}

Вот функция контроллера, где файл сохраняется во временную папку

#region ExportErrorToExcel
    //This function will return the file name to script
    public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
    {

        UA patsUA = Session["PaTSUA"] as UA;
        DataTable dataTable = null;
        dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);

        string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString()+ ".xlsx");            

        _dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
        string fname = Path.GetFileName(tempPath);

        return Json(new { Result = "true", Message = "Success", FileName = fname,Entity=entityvalue });
    }
    #endregion ExportErrorToExcel

Вот вторая функция контроллера для загрузки файла из папки Temp

#region DownloadErrorData

    //In this function recieve the filename and will download it from the location
    public ActionResult DownloadErrorData(string fname)
    {
        string fileName ="ErrorList.xlsx";
        string filePath= Path.Combine(Server.MapPath("~/Temp/" + fname));
        try
        {
            string[] allFiles = Directory.GetFiles(Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar);
            foreach (string file in allFiles)
            {
                FileInfo fileinfo = new FileInfo(file);
                if (fileinfo.CreationTime < DateTime.Now.AddDays(-2))
                {
                    fileinfo.Delete();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//web content type of .xlsx files
        return File(filePath, contentType, fileName);
    }
    #endregion DownloadErrorData

Надеюсь, это кому-нибудь поможет:)

0 голосов
/ 20 января 2019

Попробуйте это

//Exporting errors to excel file
function ExcportErrorListToExcel() {
    debugger;
    $.ajax({
        url: 'Import/ExportErrorToExcel',
        type: 'GET',
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        //contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        success: function (returnValue) {
            debugger;  
            var link=document.createElement('a');
            document.body.appendChild(link);
            link.href="/Temp/" + returnValue.filename;
            link.click();
            link.remove();
        }
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...