【问题标题】:Send byte array from code behind to ajax call将字节数组从后面的代码发送到 ajax 调用
【发布时间】:2018-10-08 20:52:59
【问题描述】:

我有一个网络方法,我将 HTML 转换为 PDF,然后将其保存到本地文件夹,我希望用户下载该文件而不发回,所以我正在尝试进行 AJAX POST 调用进入web方法获取字节数组,然后将其转换为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)
    }
});

有什么想法吗?

谢谢。

【问题讨论】:

  • dataType 不应该是“json”,我不认为it supports bytes。您可能想使用不同的 api。
  • 可能是try this?
  • 我确定这种方法应该可以工作,因为这实际上是我将 word 文件转换为字节数组的方法的复制粘贴,不同之处在于在这种情况下文件是位于文件夹中,我的其他方法在数据库中有文件,这就是为什么我不知道为什么这特别不起作用。
  • 有趣,好像不应该用。

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


【解决方案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>

【讨论】:

    【解决方案2】:
     var jsonResult = Json(model, JsonRequestBehavior.AllowGet);
                jsonResult.MaxJsonLength = int.MaxValue;
                return jsonResult;
    

    这样就可以返回最大字节数组,可以转成PDF下载了

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 2013-11-07
      • 1970-01-01
      • 2011-02-28
      • 2014-09-15
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多