AJAX呼叫控制器

时间:2017-05-25 13:35:20

标签: c# jquery ajax pdf

我在向控制器成功调用AJAX后尝试显示PDF。我需要修改我这样做的原始方式,以便能够处理多个PDF以返回单个PDF。

旧方式:

var uri = '../api/Controller/' + string1 + "," + string2 + "," + string3;
var src = '../web/printViewer.html?file=' + encodeURIComponent(uri);
window.open(src, "_blank");

所以我试图通过这样的AJAX调用来保持其功能:

$.ajax({
    type: 'get',
    url: '../api/Controller',
    contentType: 'application/json; charset=utf-8',
    data: { thing1: item, thing2: item2 },
    datatype: 'json',
    success: function (result) {
        // no bueno D:
        // but I get back a proper PDF every time
    },
    error: function () {
        toastr.error('Error creating print.');
    }
});

和C#控制器:

[HttpGet]
public HttpResponseMessage Get(string thing1, string thing2) //thing2 will be a string[] eventually, once I am able to get 2-3 pdfs working
{
    byte[] data = response.PDFBytes[0] == null ? new byte[0] : response.PDFBytes[0];
    int length = response.PDFBytes[0] == null ? 0 : response.PDFBytes[0].Length;

    var stream = new MemoryStream(data, 0, length, true, true);

    result.Content = new ByteArrayContent(stream.GetBuffer());

    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CheckedOutItems.pdf"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}

我尝试做的第一件事就是将整个事物变成一个大字符串,但只用了几个PDF就太长了。我知道控制器正在返回一个可靠的PDF,但我似乎无法在printViewer窗口中显示它。

提前致谢!!

编辑:

我不是要下载文件。我只想在新窗口中打开它,以便用户可以打印它。在开发人员尝试下载PDF的情况下,有人曾两次建议同一篇文章。那不是我追求的。

2 个答案:

答案 0 :(得分:1)

我在这种情况下最终要做的是将文件保存到磁盘,然后在AJAX调用成功后,我将从磁盘中获取PDF并显示,然后小心删除PDF之后从磁盘。我根本不想保存它,但我没有看到另一种方式。

我找到这个解决方案的原因是新窗口实际上是在它进入控制器之前打开以获取图像,但是当我做了ajax调用时,然后尝试在新窗口中打开它,它不会' t玩得很好,导致另一次调用服务器。

$.ajax({
    type: 'get',
    url: '../api/Controller',
    contentType: 'application/json; charset=utf-8',
    data: { thing1: item, thing2: item2 },
    datatype: 'json',
    success: function (result) {
        var uri = '../api/GetPDFOffDisk/ + pdfName;
        var src = '../web/printViewer.html?file=' + encodeURIComponent(uri);
        window.open(src, "_blank");
    },
    error: function () {
        toastr.error('Error creating print.');
    }
});

在从服务调用接收pdf的控制器中(在创建MemoryStream之后实现):

using (Filestream fs = new File.OpenWrite(_path))
{
    stream.WriteTo(fs);
    file.Dispose();
}

在新控制器中从磁盘中获取并返回PDF:

if (File.Exists(_path))
{
    using (FileStream file = System.IO.File.OpenRead(_path))
    {
        var data = File.ReadAllBytes(_path);
        int length = data.Length;
        MemoryStream ms = new MemoryStream(data, 0, length, true, true);
        result.Content = new ByteArrayContent(ms.GetBuffer());
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = id + ".pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        file.Dispose();
    }
    File.Delete(_path);
}

答案 1 :(得分:0)

inn您的控制器将您的字节数组(pdf文件字节)保存到临时文件,并让您的控制器返回临时文件的链接并在另一个选项卡中打开它

[HttpGet]
public HttpResponseMessage Get(string thing1, string thing2) //thing2 will be a string[] eventually, once I am able to get 2-3 pdfs working
{
    byte[] data = response.PDFBytes[0] == null ? new byte[0] : response.PDFBytes[0];
    int length = response.PDFBytes[0] == null ? 0 : response.PDFBytes[0].Length;

    var stream = new MemoryStream(data, 0, length, true, true);

    result.Content = new ByteArrayContent(stream.GetBuffer());

    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CheckedOutItems.pdf"
    };
    string TempPath="~/YourFileTempPath.pdf";
    using (FileStream file = new FileStream(Server.MapPath(TempPath), FileMode.Create, FileAccess.Write)) {
    stream.WriteTo(file);


    return Json(TempPath,JsonBehavior.AllowGet);
}

和你的Js代码

$.ajax({
    type: 'get',
    url: '../api/Controller',
    contentType: 'application/json; charset=utf-8',
    data: { thing1: item, thing2: item2 },
    datatype: 'json',
    success: function (result) {
       window.location.href=result;
    },
    error: function () {
        toastr.error('Error creating print.');
    }
});