Sending a file back to a client browser from Java after using jQuery.post() is easier than you may think

Assistance required with sending an xlsx-file from the server to the client

This is how it was done BEFORE:

JavaScript (click #export_xls button):

export_xls: function(event) {
        window.location = ... + this.workspace.query.id + "/export/xls";
}

Java (creating xls-file using Apache POI API):

@GET
@Produces({"application/vnd.ms-excel" })
@Path("/{queryname}/export/xls/{format}")
public Response getQueryExcelExport(
        @PathParam("queryname") String queryName,
        @PathParam("format") @DefaultValue("flattened") String format){
    // ...
    try {
        byte[] doc = olapQueryService.getExport(queryName,"xls","flat"); // file

        String name = "file.xls";
        return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
                "content-disposition",
                "attachment; filename = " + name).header(
                        "content-length",doc.length).build();
    }
    catch (Exception e) {
        log.error("Cannot get excel for query (" + queryName + ")",e);
        return Response.serverError().build();
    }
}

It worked well in the past, but now there's a need to transfer data from JavaScript to Java, which will process it and create an xlsx file. This involves using ajax to send the data in JSON format...

export_xls: function(event) {
        var data = this.workspace.query.result.lastresult();
        var url = ...  + this.workspace.query.id + "/testexportxls";
        $.ajax({
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            async: false,
            contentType: "application/json"
        });
    },

...and then creating the file in Java (similar to the previous method):

@POST
@Produces({"application/vnd.ms-excel" })
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{queryname}/testexportxls")
public Response setQueryExcelExport(final Object jsonData)
{
    Workbook wb = MyFileBuilder.getFile(jsonData);
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        wb.write(bout);

        byte[] doc = bout.toByteArray();

        String name = "file.xlsx";
        return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
                "content-disposition",
                "attachment; filename = " + name).header(
                "content-length",doc.length).build();
    }
    catch (Exception e){
        log.error("Error while xlsx-file creating. Exception message: ",e);
        return Response.serverError().build();
    }
}

But retrieving the file seems to be problematic now, possibly due to the use of ajax.

Is there a quick solution that requires minimal code changes?

Unfortunately, I have limited knowledge about Response, HttpServletResponse, and similar concepts. Any help would be appreciated.

Thank you for your time.

Answer №1

Is it possible for a callback function to manage the file if it is defined as successful?

It doesn't appear so, maybe another approach would be better: embedding the JSON in a concealed form input and submitting it through POST?

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

Using JQUERY for navigating through pages in a REST API while utilizing deferred functionality

I am utilizing a REST API in jSON format to fetch records. My Approach The REST API retrieves records in jSON format. Initially, I retrieve the top 6 records, along with an additional jSON node containing a forward paging URL. This URL is assigned t ...

Encountering an error while using *ngIf to filter within a loop in Angular

I'm having trouble using *ngIf to filter out items in a list generated by looping, and it's throwing an error. Can someone please assist me with this issue? abc.component.html <ul> <li *ngFor="let x of students" *ngIf="x.age < ...

Is it possible to conceal specific sections of a timeline depending on the current slide in view?

For my product tour, I've structured a timeline with 4 main sections, each containing 4-5 subsections. Here's how it looks: <ul class="slideshow-timeline"> <li class="active-target-main main-section"><a href="#target">Targe ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

Retrieve information from the API every second

In my React Native app, I have a system where customer orders are fetched and displayed on the restaurant side in a specific screen. I'm using the Fetch API to retrieve this data. The workflow is as follows: the customer places an order, which is then ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

Navigating to the header tab in React Native and accessing a variable

I have implemented a switch in my tab header, and I am looking to retrieve the value of the switch every time it is toggled. How can I accomplish this? const navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; ret ...

Error: The initialization of the org.elasticsearch.common.lucene.Lucene class failed, resulting in a java.lang.NoClassDefFoundError

When attempting to write on ES using a Hadoop job, the system freezes and generates logs with the following error: Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.common.lucene.Lucene. What could be causing this is ...

Searching for all Related Rows and Updating Them in Java/Oracle

In my Oracle database, I have a table named COMBO_VALUES that is referenced by various other tables. For instance, a single record in COMBO_VALUES could be referenced by as many as 100 different tables. My goal is to identify all the related records (thei ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

Retrieving data from an Array containing a mix of string and integer values represented as strings, organized by the length of the

Imagine you have an array structured like this: employeeArr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000'] Where employeeArr[0] and employeeArr[2] represent employee names, and employeeA ...

Several different forms are present on a single page, and the goal is to submit all of the data at

Looking for assistance with combining Twitter and Google data entry at once. Here's the code I've developed: Please guide me on how to submit Twitter and Google details together. <html> <head> <script type="text/javascript">< ...

Use jQuery to transfer groups of table rows to a newly relocated table data cell

First of all, I appreciate you taking the time to go through this explanation. My current challenge involves using jQuery to move sets of TRs to new positions in a table. While I can easily move the headers, I am facing difficulty with moving the actual da ...

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

Determine if an Image is Chosen upon Click with Javascript

I am currently working on a wysiwyg editor and I'm facing an issue where I need to determine if a user has clicked on an image within the selection range. Is there a method to detect this without attaching event handlers directly to the image itself? ...

Guide to building a simple AngularJS webpage to fetch and display RESTful JSON data

I am in the process of developing a simple webpage that displays data retrieved from http://rest-service.guides.spring.io/greeting. The JSON output looks like this: {"id":2273,"content":"Hello, World!"} This is the HTML code I am using: <body ng-app ...

Exploring the Benefits of Employing PHP's json_encode Function with Arrays

$cnt = 0; while ($row = $result->fetch_assoc()) { $arre[$cnt]['id'] = $row['idevents']; $arre[$cnt]['title'] = $row['title']; $arre[$cnt]['start'] = "new Date(" . $row['start'] . " ...

What is the best way to include variable child directives within a parent directive in AngularJS?

Exploring a New Angular Challenge In the current project I am engaged in, I am faced with a unique problem that requires an 'angular way' solution. Despite my best efforts, I seem to be hitting a roadblock every time I attempt to solve it. The ...

Effortlessly add data to Codeigniter using the power of ajax

Can an associative array be utilized with Ajax for CRUD operations to insert data without reloading the page and appending it below existing data? JavaScript Code function addTextBox(section, id_group) { row_section = "#row_" + section; wrapper = $(row_s ...

Third Party Embedded Video requiring SSL Certificate

I am currently facing an issue where I am trying to embed videos from a website that does not have an SSL certificate. This is causing my own website to appear insecure when the page with the embedded video loads, despite the fact that my website has its ...