将字节数组从后面的代码发送到Ajax调用

时间:2018-10-08 20:52:59

标签: javascript c# asp.net .net webmethod

我有一个Web方法,其中我将HTML转换为PDF,然后将其保存到本地文件夹,我希望用户下载该文件而不进行回发,因此我尝试进行AJAX POST调用进入网络方法以获取字节数组,然后将其转换为PDF,问题是我收到了错误500:

{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}

尽管我知道Web方法会触发,因为当放置断点时,它会在那里停止,并且实际上我可以在返回之前看到二进制数组以及文件夹中创建的文件,但仍然收到错误消息,这是代码:

C#:

[WebMethod]
public static byte[] getfile(string one, string two)
{
    HttpContext context = HttpContext.Current;
    HtmlToPdf converter = new HtmlToPdf();

    converter.Options.MinPageLoadTime = 10;
    converter.Options.MaxPageLoadTime = 30;

    PdfDocument doc = converter.ConvertUrl("http://localhost/dashboard_pdf.aspx?one=" + one+ "&" + "two=" + two);

    string appPath = HttpContext.Current.Request.ApplicationPath;
    Random rnd = new Random();
    int num = rnd.Next(1, 1000000);
    string path = context.Server.MapPath(appPath + "/Web/" + num + ".pdf");

    doc.Save(path);   
    doc.Close();

    FileStream stream = File.OpenRead(path);
    byte[] fileBytes = new byte[stream.Length];

    stream.Read(fileBytes, 0, fileBytes.Length);
    stream.Close();

    byte[] b1 = System.IO.File.ReadAllBytes(path);

    return fileBytes;
}

JS:

$.ajax({
    type: "POST",
    url: "dashboard.aspx/getfile",
    contentType: "application/json; charset=utf-8",
    data: "{'one':\"" + one+ "\", 'two':\"" + two + "\" }",
    dataType: "json",
    processData: false,
    success: function (data) {
        data = data.d;

        var byteArray = new Uint8Array(data);
        var a = window.document.createElement('a');

        a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));

        a.download = "Dashboard";

        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
    }
});

有什么想法吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

我通过将其添加到我的web.config中来解决此问题:

 <system.web.extensions>
    <scripting>
      <webServices>
        <!-- Update this value to change the value to a larger value that can accommodate your JSON Strings -->
        <jsonSerialization maxJsonLength="86753090" />
      </webServices>
    </scripting>
  </system.web.extensions>

答案 1 :(得分:0)

 var jsonResult = Json(model, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;

通过这种方式,您可以返回最大字节数组,并且可以转换为PDF并下载