如何使用Ajax方法下载excel文件-我的文件是在Temp文件夹中下载的,而不是在Browser中下载的?

时间:2019-01-19 13:05:05

标签: c# jquery ajax

我想下载一个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 :(得分:0)

尝试一下

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

答案 1 :(得分:0)

这可以简单地通过将控制器功能分为两个来完成。第一个功能将 将文件保存在temp文件夹中,然后将文件名传递给jquery 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();
}

这是Controller功能,文件保存在临时文件夹中

#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

希望这对某人有帮助:)