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

1- Измените значение переполнения-y на видимое и удалите атрибут overflow-x.

   .list-wrapper {
      overflow-y: visible;
    }

2- Затем измените значение переполнения-y на auto.

 .outer {
      overflow-y: auto;
    }
0
задан Dhanil Dinesan 20 January 2019 в 09:18
поделиться

2 ответа

Это можно сделать, просто разделив эту функцию контроллера на две. Первая функция сохранит файл во временной папке и передаст имя файла функции 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
[116 ] Вот вторая функция контроллера для загрузки файла из папки 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
ответ дан Dhanil Dinesan 20 January 2019 в 09:18
поделиться

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

//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();
        }
    });
}
0
ответ дан Udara Kasun 20 January 2019 в 09:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: