繁体   English   中英

C#ASP.NET MVC:如何让浏览器从我的响应中自动下载pdf?

[英]C# ASP.NET MVC: How do I get the browser to automatically download a pdf from my response?

我创建了一个ASP.NET MVC Web应用程序,我通过AJAX帖子从客户端接受一些信息,并使用iTextSharp创建一个pdf。 在向客户端返回响应时,我希望浏览器自动在用户的计算机上下载pdf。 我开始实际上将文件保存到文件夹并返回绝对路径,所以我知道代码生成了pdf成功。 但是,我没有返回实际路径,而是读到我可以将其存储在MemoryStream中并将其放入我的响应中。 我已经尝试返回实际的MemoryStream,将其转换为字节数组并返回它,返回FileStreamResult,并将MemoryStream添加到Response,但似乎没有任何工作。 我知道有类似的问题,但我找到的代码都没有解决我的问题。 有人可以请告诉我我需要在代码中更改哪些内容才能完成此操作,好吗?

AJAX代码:

.ajax({
    url: "/Reports/GenShoppingList",
    type: "Post",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(recipeIdArray),
    datatype: "application/pdf"
 });

Pdf创建和响应代码:

public static void GenShoppingListPDF(StringBuilder ingredientNames)
{
    MemoryStream MemoryStream = new MemoryStream();
    doc = new Document();
    PdfWriter.GetInstance(doc, MemoryStream).CloseStream = false;
    doc.Open();
    doc.Add(new Paragraph(ingredientNames.ToString()));
    doc.Close();
    string fileName = "ShoppingList-" + DateTime.Now.ToString() + ".pdf";
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ContentType = "application/pdf";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.BinaryWrite(MemoryStream.ToArray());
    response.Flush();
    response.Close();
    response.End();
}

StringBuilder对象通过控制器操作传递给代码,该操作只是创建对象并调用此静态方法。 控制器操作返回类型为void。

最终解决方案:通过进一步的研究和讨论,我得出结论,JQuery AJAX不支持发布数据和返回pdf。 相反,最好只使用简单的XMLHttpRequest并放弃使用JQUERY。

查看您正在使用的库,这对我有用,并正确下载文件。

public ActionResult File()
{
  string ingredientNames = "Hello David";
  using (MemoryStream stream = new MemoryStream())
  {
    var doc = new Document();
    PdfWriter.GetInstance(doc, stream).CloseStream = false;

    doc.Open();
    doc.Add(new Paragraph(ingredientNames.ToString()));
    doc.Close();

    return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "file.pdf");
  }
}

最终解决方案:通过进一步的研究和讨论,我得出结论,JQuery AJAX不支持发布数据和返回pdf。 相反,最好只使用简单的XMLHttpRequest并放弃使用JQUERY。

暂无
暂无

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

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