Initiate a POST ajax request to retrieve the file.Let's

I'm currently working on an Asp.Net MVC project and I have a piece of code in my View that looks like this:

$.ajax({
        beforeSend: function () {
            LoadStart();
        },
        complete: function () {
            LoadStop();
        },
        //async: false,
        contentType: 'application/json, charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '@Url.Action("MyAction", "MyController")',
        data: JSON.stringify(
            {
                Param1: 1,
                Param2: 2
            }),
        success: function (data) {
            $("#pdf-content").show();
            // Here, fill DIV (pdf-content) with PDF.
        },
        fail: function () {
            alert("Fail");
        }
});


Within the MyAction method, I have the following code:

[HttpPost]
public ActionResult MyAction(int Param1, int Param2)
{
    // Code ...

    MemoryStream stream = new MemoryStream();
    outPdf.Save(stream);
    byte[] fileContents = stream.ToArray();

    return File(fileContents, "application/pdf", "myFile.pdf");
}


I am wondering how I can display the PDF content directly within a DIV element or even download it without displaying it. Any suggestions on how to achieve this?

Answer №1

The optimal approach here would be to: Save the file on the server using a unique identifier (such as a GUID) in the POST method and send this identifier back to the client.

Subsequently, send a GET request to retrieve the file using the provided GUID, serve it to the client, and then remove it from the server.

Additionally, consider implementing a service to automatically delete old files for better efficiency.

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

Encountering a serialization error when trying to load a JSON file

Below is a JSON file example: [ { "applicationConfig": { "Name": "Name1", "Site": "Site1" }, "pathConfig": { "SourcePath": "C:\\Temp\\Outgoing1", "TargetPath": "C:\\Files" }, "cre ...

The Strophe.muc plugin and backbone improper binding of callbacks

Following the initial group message, I'm experiencing an issue with the strophe.muc plugin not responding to subsequent messages. Although I receive the first presence, message, and roster from the room, any additional messages and presence stanzas do ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

What is the most efficient way to perform an array join in Node.js, akin to the speed of MongoDB's $

Looking to implement a $lookup function in Node.js similar to the $lookup aggregation in MongoDB. I have a solution in mind, but I'm unsure about its performance when dealing with larger arrays or bigger objects. let users = [ {userId: 1, name: ...

Utilizing NodeJS, Express, and the Jade template engine to insert JSON data into

While trying to follow a tutorial on NodeJS, Express, Jade, and MongoDB, I ran into a frustrating issue. Despite reading through various forum threads and attempting the suggested solutions, I still can't seem to make the POST command work. Please di ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

CSS3 Animation: Facing issue with forwards fill behavior in Safari when using position and display properties

After creating a CSS3 animation to fade out an element by adjusting its opacity from 1 to 0 and changing the position to absolute and display to none in the last frames, I encountered an issue. In Safari, only the opacity is maintained while the position a ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Can raw text fields be retained during deserialization?

My JSON data is structured like this: { "guid": "b1e3c29f-066f-417b-b6b6-795ffae90f0a", "status": "complete", "type": "colors", "results": { "events" ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

Tips for keeping a Youtube video playing even after the page is refreshed

Is it possible to save the current position of a Youtube video and have it resume from that point when the page is refreshed, instead of starting from the beginning? I am considering using cookies to store the last position or utilizing GET. Although my w ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

Node.js: Extract the object's name and value that are sent from the frontend

I'm in the process of creating a microservice using nodejs. The request is returning the following JSON. { "distCd": "abcd", "distName": "parentLife Distributor (TOD)", "stateCd": "", "subdistInd": false, "maindistInd": true ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...