在mvc4中调用ajax文件下载c#

时间:2014-03-26 07:24:37

标签: c# ajax asp.net-mvc-4

我正在向控制器发出ajax调用。我正在创建一个pdf文件。

如何将其发送到浏览器以便用户可以下载。

    [HttpPost]
    public void Createpdf(string htmlpage)
    {
        var htmlToPdfConverter = new HtmlToPdf();
        string htmlCode = "<!DOCTYPE html><html lang='en'><head><title>Report</title>/head><body>" 
            + htmlpage 
            + "</body></html>";
        string baseUrl = null;
        pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, baseUrl);
        System.IO.File.WriteAllBytes(@"D:\HubReport.pdf", pdfBuffer);
        //System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
        //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
        //   String.Format("{0}; filename=HubReport.pdf;size={1}", "attachment", pdfBuffer.Length.ToString()));
        //System.Web.HttpContext.Current.Response.BinaryWrite(pdfBuffer);
        //System.Web.HttpContext.Current.Response.End();
    }

1 个答案:

答案 0 :(得分:1)

我没有对此进行过测试,但这可能会给你一些指示。

您将文件名传递给此操作。并将此操作作为新窗口的URL。

public FileResult Getfile(string downloadfileName)
{
    byte[] fl = System.IO.File.ReadAllBytes(@"C:\temp\" + downloadfileName);
    string fileName = "Somefile.pdf";
    return File(fl, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

修改

我对此进行了测试,它的工作非常精细

这是我的示例视图代码

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<script type="text/javascript">
    $(document).ready(function () {
        //You need to call this click function from you ajax Success callback.
        $("#getFile").click(function () {
            window.open('@Url.Action("GetFile","Home","test.pdf")', "downloadfile");
        });
    });

</script>
<input type="button" value="GetFile" id="getFile" />

这是控制器

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public FileResult Getfile(string downloadFileName)
    {
        byte[] fl = System.IO.File.ReadAllBytes(@"C:\temp\sampleFile.pdf");
        string fileName = "Somefile.pdf";
        return File(fl, System.Net.Mime.MediaTypeNames.Application.Octet);
    }
}

这是输出

Sample output