Pass a byte array from the back-end code to an AJAX request

I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retrieve the byte array and convert it into a PDF. However, I keep encountering a 500 error:

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

Despite confirming that the web method is being triggered (as evidenced by breakpoints stopping there and observing the binary array before the return statement, as well as the file created in the folder), the error persists. Below is the code snippet:

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)
    }
});

Any suggestions on how to resolve this issue?

Thank you.

Answer №1

To resolve this issue, I made a modification to my web.config file like so:

 <system.web.extensions>
    <scripting>
      <webServices>
        <!-- Ensure that the maxJsonLength value is set high enough to handle your JSON data effectively -->
        <jsonSerialization maxJsonLength="86753090" />
      </webServices>
    </scripting>
  </system.web.extensions>

Answer №2

 let resultJson = JsonData(dataModel, AllowJsonRequest.Get);
            resultJson.LimitToJsonMax = MaximumIntValue;
            return resultJson;

By following this approach, you'll retrieve the largest byte array possible which can then be converted to a PDF file for downloading.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...

Adding a button input and deleting non-functional parent elements

Here is a simple append function using jQuery, and it's working perfectly. However, the issue arises when I try to append a button and remove the parent tr upon clicking. The problem lies in using remove parent, as it doesn't seem to work as exp ...

Retrieve the JSON data based on a specific key after a specified period

Hello there, I am encountering an issue with a specific JSON key. Let's say I have an external file containing JSON data structured like this: { "key 1":[ { "linkName":"key name 1.1", "linkUrl":"key URL 1.1" }, ...

What is the process for using the GitHub API to access a repository's README document?

For my project, I'm utilizing the GitHub API to access the raw README.md file using /repos/{owner}/{repo}/readme. I've successfully executed the call using Thunderclient in VSCode and retrieved the raw file. https://i.sstatic.net/FtkfW.png Howev ...

Encountering an error: [nsIWebProgressListener::onStatusChange] when utilizing jQuery AJAX within a click event?

Greetings! I am currently learning how to implement AJAX with jQuery to load an HTML document into a div element within another HTML document. Here is the approach I am using: function pageload() { $.ajax({ url: 'Marker.aspx', ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Combining properties from one array with another in typescript: A step-by-step guide

My goal is to iterate through an array and add specific properties to another array. Here is the initial array: const data = [ { "id":"001", "name":"John Doe", "city":"New York&quo ...

Creating a Website for Compatibility with NoScript

During my journey of building a nameplate site from the ground up for myself, I have delved into the realms of learning and establishing my online presence. The highlight of my project is a sleek tabbed site that employs AJAX and anchor navigation to seaml ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

Javascript: regular expression to validate alphanumeric and special characters

Looking to create a regular expression for a string (company/organization name) with the following conditions: No leading or trailing spaces No double spaces in between Shouldn't allow only a single character (alphanumeric or whitelisted) Can start ...

What is the best way to extract the information from the checkbox in a MUI datatable?

I am struggling to transfer an array with checked values to another table in order to display only those values. How can I achieve this? I am relatively new to using react and I find it challenging to grasp how some of the functions and components work. I ...

The folder serves as a module, however, the index.js file within the folder only consists of a few require

Currently, I am delving into the source code of hexo, a project built on top of node.js. Specifically, I came across a file named init.js: if (results.config){ require('./plugins/tag'); require('./plugins/deployer'); require('./pl ...

Automatically install the development version of NW.js when running 'npm i'

Is it possible to automate the installation of the developer version of NWJS from package.json, similar to when I run npm install? For example, if I type npm i nw --nwjs_build_type=sdk I attempted to set an environment variable in my package.json like th ...

Is there a way to convey a transition MUI property from a parent component to its child component in React?

My current setup involves a parent component with a button that triggers the opening of a snackBar from MUI (child component) upon click. To enhance the user experience, my teacher suggested adding a transition effect to the onClick event so that the snack ...

Display debugging information in the console using bunyan

child.log.info('info'); child.log.debug('debug'); When running the command: node app.js | bunyan -o short -l debug I am encountering an issue where only INFO messages are displayed and DEBUG messages are not showing up. I want to be ...

A Step-by-Step Guide to Downloading Images by Clicking

Having an issue with my image download code. When I try to download an image, the process starts but doesn't complete and no file is received. Instead, a type error is encountered. <html> <head> <script type="text/javascript"> funct ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

Removing files from the S3 bucket and database simultaneously. Execute each function sequentially

Struggling with an API call that should delete an image from both an S3 bucket and a MySQL database. However, encountering an issue where the S3 image cannot be found because it is being deleted from the database first. // Router code: //req.body is an ar ...