Step by step guide on downloading an Excel file using Ajax technology

I am facing difficulties in downloading an Excel file using Ajax. I came across this code on another website and implemented it in my project:

$.ajax({
          type: "POST",
          url: "myStrutsAction.action",
          data: {p1:p1, p2:p2},                      
          success:  function(response, status, xhr){                                     
                          disableMyLoadingUserPopupScreen();                                                              

                            var filename = "";
                            var disposition = xhr.getResponseHeader('Content-Disposition');                             
                            if (disposition && disposition.indexOf('attachment') !== -1) {                                  
                                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                                var matches = filenameRegex.exec(disposition);
                                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                               disposition);                                    
                            }

                            var type = xhr.getResponseHeader('Content-Type');                              
                            var blob = new Blob([response], { type: type });

                            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                                 window.navigator.msSaveBlob(blob, filename);
                            } else {
                                var URL = window.URL || window.webkitURL;
                                var downloadUrl = URL.createObjectURL(blob);                                   

                                if (filename) {                            
                                    var a = document.createElement("a");                                        
                                    if (typeof a.download === 'undefined') {
                                        window.location = downloadUrl;

                                    } else {
                                        a.href = downloadUrl;
                                        a.download = filename;
                                        document.body.appendChild(a);
                                        a.click();
                                    }
                                } else {
                                    window.location = downloadUrl;                                      
                                }

                                setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); 
                            }
                        }   
                    });     

This script helps prompt the user to save or open the specific Excel file. However, when trying to open the file, it appears damaged with unreadable characters in Notepad++:

Below is my Struts2 execute method on the server:

public String execute(){

   // Create Excel File
   returnFileAsStream("myExcelfile");

   return null;
}

In this method, I set the HTTP Response Header as follows:

private void returnFileAsStream(final String filename) throws IOException {
    final InputStream is = new FileInputStream(filename);
    OutputStream os = null;
    try {
        response.setContentType("application/octet-stream");            
        response.setHeader("Cache-Control", "maxage=3600");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");             
        os = response.getOutputStream();

        int length;
        byte buf[] = new byte[1024];
        while ((length = is.read(buf)) > 0) {
            os.write(buf, 0, length);
        }           
        is.close();
        os.close();         
    } finally {
        // additional code here                       
    }       
}

Could it be that handling file downloads with Ajax is not feasible? Perhaps the issue lies in trying to manage binary data with Ajax, which may not fully support binary operations?

Answer №1

To specify the content type:

For files saved in BIFF format as .xls:

Use application/vnd.ms-excel

For files saved in Excel2007 and later as .xlsx:

Use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

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

Utilizing Angular and the Kendo UI framework to customize the dimensions of a Kendo window

Is there a way to dynamically set the height and width of the kendo window based on the content of the kendo grid? Below is the code snippet for my kendo-window: <div kendo-window="Operation.OperCustWind" k-width="800" k-height="700" ...

The Jquery ajax function fails to execute after upgrading the framework version from 3.5 to 4.0

After testing with alert, I am facing an issue where the ajax call is not working in my aspx.cs file when switching from .NET framework 3.5 to 4.0. The ajax function being used is: function GetCustomers(pageIndex) { $.ajax({ t ...

Is there a way to get rid of this awful hover effect on this button?

My friend and I have been developing a Chrome extension for the Roblox Devforum with some initial success. We started working on it yesterday, and already have our button placed in the header similar to extensions like Roblox+ or RoPro. However, we encoun ...

Saving an Excel file using FileInputStream: When a file format does not match its extension

Having an issue while attempting to save an xls file. Everything seems to be working fine, but upon opening the file, I encounter the error "A file is in a different file format than its extension indicates". It appears that the file has become corrupted ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Simplified method of connecting dynamic components without needing to remember functions in jQuery

I have a page where users can freely move, resize, and modify content. The basic setup is as follows: $('.element').on().resizable().draggable(); When this code is called on page load, it allows elements to be resizable and draggable. The issu ...

Discovering the most efficient route among a collection of objects in JavaScript

Presented here is an array of objects: const data = [ { start: "X", end: "Y", distance: 5}, { start: "X", end: "Z", distance: 4}, { start: "Z", end: "Y", distance: 8}, { start: "Y", end: "V", distance: 9}, { start: "V", end: "Z", dista ...

Is WooCommerce causing a blockage for AJAX requests to successfully return?

I'm completely confused by this situation. We've implemented a script in functions.php that utilizes AJAX to add products to the cart: function add_to_cart() { $multipleProducts = $_POST['multipleProducts']; $productsArray = $_ ...

Sending real-time events to a single client using pusher, pubnub, or socket.io

I'm currently working on a multiplayer turn-based game that uses Pusher for establishing communication between clients and server. While I can send events to all clients using game channels, I'm facing an issue in sending an event to a single cli ...

Issue with JQuery plugin functionality when utilized repeatedly on a single page

Creating a unique JQuery plugin called grid2carousel has been my recent project. The plugin is designed to transform content displayed in a Bootstrap-style grid on desktop devices into a functional carousel on smaller screens. Although the plugin function ...

Running PHP database commands within JavaScript

My issue involves a list that can have one or more tasks attached to it. Here's how the process works: When a user attempts to delete the list, a PHP code checks the 'tasks' table in MySQL to see if any tasks are linked to the list being d ...

Unable to output an ajax .load function using PHP

$commentID = $row['comment_id']; $editedCommentID = "edit" . $commentID; echo "$('#".$editedCommentID."').load('editcomments.php')"; There seems to be an issue with the .load function in the code snippet above. I have been s ...

Unable to define an object within the *ngFor loop in Angular

In order to iterate through custom controls, I am using the following code. These controls require certain information such as index and position in the structure, so I am passing a config object to keep everything organized. <div *ngFor="let thing of ...

Encountering "Unexpected token *" error when using Jest on an import statement

What could be the reason for Jest failing with the error message "Unexpected token *" when encountering a simple import statement? Error log: Admin@Admin-PC MINGW32 /d/project (master) $ npm run test > <a href="/cdn-cgi/l/email-protection" class="__ ...

Jetty's http2 feature allows for the opening of multiple connections to the same destination

Utilizing the Jetty client for establishing HTTP2 connections with servers that support HTTP2. The Jetty client efficiently handles opening connections as needed and facilitates data exchange between endpoints. Below is a snippet of code showcasing how to ...

Dealing with a POST array object in JSON format while preventing the occurrence of the ECONNREFUSED error that results

I have a data.json file containing an array of objects with around 4000 entries, each object having approximately 200 properties. However, when I try to read this file and POST it to a loopback API, I encounter an error message stating "ECONNREFUSED Socket ...

Utilizing the res directory over the sdcard storage solution

I need to transfer files from my sd card to an apk file, specifically in the res/raw folder. How should I modify the string to access that folder? f = new File("/sdcard/file.ext"); ...

The performance of Three.js significantly decreases when utilizing onMouseMove in conjunction with RayCaster

I am currently working on an application using three.js, but I am encountering serious performance issues. This particular part of the application is inspired by the Voxel Painter example. In my version, the user initiates placement by clicking on a cell, ...

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...