将字节数组从代码隐藏发送到 ajax 调用



我有一个Web方法,其中我将HTML转换为PDF,然后将其保存到本地文件夹,我希望用户下载该文件而不进行回发,所以我正在尝试对Web方法进行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)
}
});

有什么想法吗?

谢谢。

我通过将其添加到我的 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>
var jsonResult = Json(model, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;

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

最新更新