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

Intermittent AJAX 403 Forbidden errors occur from time to time

My goal here is to validate whether a username is already taken in real-time as the user types, triggering an AJAX call on keyup event to check if it's available. If the username is taken, the input field will be highlighted in red. However, I've ...

Error message occurs in jQuery form when optional fields are left empty, displaying a "missing ) after argument list" notification

I've encountered an issue with my form that submits to a jQuery plugin I developed. Until now, everything worked smoothly, but when I added optional fields to the form, things started going wrong. The input text fields in the form are initially popula ...

React - Render an element to display two neighboring <tr> tags

I'm in the process of creating a table where each row is immediately followed by an "expander" row that is initially hidden. The goal is to have clicking on any row toggle the visibility of the next row. To me, it makes sense to consider these row pa ...

Difficulty encountered in resetting progress bar post ajax form submission

Hello, I hope you can assist me with an issue I am facing regarding my progress bar. After submitting the form using AJAX to insert data, my progress bar does not reset. I would like it to reset after clicking the submit button. The progress bar is speci ...

Tips to instantiate an object of a different JavaScript class in Node.js

Hey there! I'm having trouble creating an instance of ProfileComparator in a different JavaScript file called index.js. Can someone help me resolve this error? strategy.js var cosineUtils = require("./jscosine"); var ProfileComparator = function(al ...

Snatching the lesson found within an iframe

Is it possible to obtain the id from an iframe using the following method? var iFrame = window.top.document.getElementById('window_<?php echo $_product->getId() ?>_content'); However, I am struggling to understand how to retrieve the c ...

A step-by-step guide on activating dark mode for the markdown-it-vue plugin while incorporating Vuetify styling

I'm looking to display some documentation in my Vue application. The documentation is in markdown format, so I have already integrated the markdown-it-vue plugin. However, I've run into an issue where the plugin doesn't support vuetify dark ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Steps for updating a value in a JSON file using PHP

Trying to modify a value within a JSON file for a specific object is throwing me off balance. The issue arises from having multiple siblings in the same JSON file sharing identical key-value pairs. The JSON structure I'm dealing with appears as follo ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

Despite my usage of className, I still encounter the error message "Error: Invalid DOM property `class`."

I am having trouble debugging this issue as I am unsure of the exact location of the error. Here is the link to the repository: https://github.com/kstaver/React-Portfolio Error #2. There are three more promise rejection errors present, which I will addres ...

Tips for resolving CORS problems when trying to pull data from an API by utilizing jQuery AJAX and a JAVA backend

Currently, I am working on developing a front-end application to display data fetched from an API. This particular API was created using JAVA and Swagger.io by an android engineer. At the moment, the API does not have any authentication mechanism in place, ...

The loading speed of this page is extremely sluggish

Hello to all! I have been struggling to address this problem with no success. The index page loads quickly, but when I log in to the dashboard and try to access other pages under a PHP session, I encounter errors in my JavaScript console - not to mention ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

What steps are involved in setting up role-based authentication using Node.js?

Essentially, I am looking for a way for nodeJS to determine if the user logging in through the login page is an admin or not. If they are an admin, they should be directed to the admin page; if not, they should be sent to a different page. Currently, I ha ...

The calculator is malfunctioning and unable to perform calculations

export default function App() { const [activeKey, setActiveKey] = useState(0); const [storeArr, setStoreArr] = useState([]); function click(selector) { setActiveKey(selector); if (activeKey !== "=") { setStoreArr([...storeArr ...

"Vue.js: The Ultimate Guide to Event Management and Data Handling

I recently started learning Vue.js and I'm having some difficulty with my coding exercises: The task is to have a menu button that opens a dropdown box when clicked, and when any selection is made, it should go back to the menu button. index.js cons ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

Challenges encountered with extracting information from a JSON dataset

When I make an Ajax POST request, the response I receive is structured like this: { "columns": [ "r" ], "data": [ [ { "extensions": {}, "start": "http://localhost:7474/db/data/node/27 ...