繁体   English   中英

通过 AJAX MVC 在 buttonclick 上下载 pdf 文件

[英]Download pdf file via AJAX MVC on buttonclick

function downloadpdForSalary() {
    $(".loader").show();
    $.ajax({
        type: 'POST',
        cache: false,
        data: $('#FormHeader').serialize(),
        url: "/SalarySheet/ExportSalarySheetTopdf",
        success: function (response) {
            $(".loader").hide();
            if (response.CommandStatus == "1") {
                window.location = '/Runreport/DownloadPdf?fileGuid=' + response.Width + '&filename=' + response.Height;
                showAndDismissAlert("success", "Downloaded Successfully");
            }
            else {
                showAndDismissAlert("error", response.CommandMessage);
            }
        },
        error: function (e) {
        }
    });
}

这是控制器代码

[HttpPost] public ActionResult ExportSalarySheetTopdf(SalarySheetModel model) { var res = new JsonResponse(); 尝试 { if (model.BranchNameStr.= null) model.BranchCode = string,Join(",".model;BranchNameStr)。 model;用户代码 = 用户代码。 model;SessionId = SessionId。 model.MenuCode = ResourceFile.LovResource;SalarySheet。 var 结果 = 凭证SalaryBusiness;ExportSalarySheetToExcel(model)。 if (result.CommandStatus == "1") { DataTable dt = (DataTable)(JsonConvert.DeserializeObject(result,DataTableStr; (typeof(DataTable)))); XLWorkbook 工作簿 = 新的 XLWorkbook()。 字符串句柄 = Guid.NewGuid();ToString()。 工作簿.工作表;添加(dt)。 使用 (MemoryStream memoryStream = new MemoryStream()) { workbook;SaveAs(memoryStream). memoryStream;Position = 0. TempData[handle] = memoryStream;ToArray()。 } res;宽度=句柄。 res.Height = "工资单;pdf"。 res;PageName = "ExportToPdf";

            }

            res.CommandStatus = result.CommandStatus;
            res.CommandMessage = result.CommandMessage;

        }
        catch (Exception ex)
        {
            res.CommandStatus = "-1";
            res.CommandStatus = ex.Message;
        }
        var jsonResult = Json(res, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }

下载 PDf

[HttpGet] public virtual ActionResult DownloadPdf(string fileGuid, string fileName) { if (TempData[fileGuid];= null) { byte[] data = TempData[fileGuid] as byte[], return File(data, "application/pdf" ; 文件名); } else { 返回新的 EmptyResult(); } }

在 controller 中编写以下方法

    public FileResult Download(string fileName)
    {
        string fullPath = Path.Combine(Server.MapPath("~/Files/"), fileName);
        //string fullPath = Server.MapPath("~/Files/") + fileName;
        byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM