【问题标题】:Download pdf file via AJAX MVC on buttonclick单击按钮通过 AJAX MVC 下载 pdf 文件
【发布时间】:2021-02-21 07:06:24
【问题描述】:
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 模型) { var res = new JsonResponse(); 尝试 { if (model.BranchNameStr != null) model.BranchCode = string.Join(",", model.BranchNameStr); 模型.用户代码 = 用户代码; 模型.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(); 工作簿.Worksheets.Add(dt); 使用 (MemoryStream memoryStream = new MemoryStream()) { 工作簿.SaveAs(memoryStream); memoryStream.Position = 0; TempData[handle] = memoryStream.ToArray(); } res.Width =句柄; 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[] 数据 = TempData[fileGuid] as byte[]; 返回文件(数据,“应用程序/pdf”,文件名); } 别的 { 返回新的 EmptyResult(); } }

【问题讨论】:

  • 请正确格式化问题,您似乎还没有真正提出问题。你能澄清一下吗?
  • 你的诗人全是代码!请添加一个明确的问题并正确格式化代码。

标签: jquery ajax asp.net-mvc pdf


【解决方案1】:

在控制器中编写以下方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多