Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below.

Thank you.

On a JSP page, there is a list of attachments, each accompanied by a Download button.

Upon clicking the Download button, a function named downloadFile(url) is called.

https://i.sstatic.net/5kM9o.png

The code on the Download button:

<button onclick= "downloadFile('ProcessControllerHelper?action=download&attachmentId=<%=attachment.getAttachmentId() %>')" class="btn btn-sm btn-round btn-default"><bean:message key="lbl.download"/></button>
    

The downloadFile function that is executed upon clicking the Download button:

function downloadFile(url)
        {
            // Code for downloading file
        }
    

Despite successfully downloading the files upon clicking the Download button, they cannot be opened as shown in the screenshot below:

https://i.sstatic.net/bGF7D.png

The problem lies in the fact that the downloaded file cannot be opened, and an error message stating "we don't support the format" is displayed:

https://i.sstatic.net/Ar3od.png

Your help would be greatly appreciated!

Answer №1

I successfully implemented the function below from a third-party API () and it worked flawlessly for me.

function downloadFile( url )
    {
        var flag = 1;
        fetch(url, {
            method: "GET",
            headers: {
                    "Content-Type": "application/json; charset=utf-8"
                }
            })
            .then(response => {
                if (response.status === 200) {
                    filename = response.headers.get("content-disposition").split(";")[1].split('"')[1];
                    return response.blob();
                } else {
                    alert('Attachment not found!');
                    flag = 0;
                    return;
                }
            })
            .then(body => {
                if(flag > 0 ) {
                    download(body, filename, "application/octet-stream");
                }
            });
    
    }

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

Deleting data from a database table using jQuery file upload

I've encountered an issue with the blueimp file upload program. The problem arises when trying to update the database table after a file has been deleted. In a scenario where two different users upload files with the same name, the records in the MyS ...

What is the best approach for transmitting data to the post method of Node.js using AJAX/jQuery?

A UDP server I have is set up to respond with a different message each time it receives a message. When I hard code the message into the variable "message," everything works fine. However, I want the client to be able to manually type in a message, and t ...

Is AJAX HTML element swapping a breeze with Rails controllers?

It would be great to have an ERB partial set up like this: <ul id='things-index'> <% @things.each do |t| %> <li><%= t.name %></li> <% end %> </ul> And have the ability to update it in the contro ...

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...

What is the best way to style a value within a v-for loop inside an el-option element in Element UI?

I'm looking for a way to format the value in label(item.value) as a decimal within a v-for loop. Below is my code snippet: <el-form-item :label="label" :required="required" prop="Jan"> <el-select v-model=& ...

The Issue of SilverStripe Custom Email Form: jQuery.ajax Failing to Pass Variables to Server

Currently, I am in the process of developing a customized email form for a SilverStripe website. This project involves a combination of jQuery, HTML, PHP, and SilverStripe API. However, I have hit a roadblock when it comes to transferring form data from th ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

What advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

Unable to enable auto-scroll feature in DIV element

My div has an auto-scroll feature that works fine, but I've encountered an issue when using multiple smileys in a single chat post. The auto scroll seems to stop working correctly and only scrolls 2 lines from the bottom. I attempted to fix this with ...

What is the best way to retrieve the current value of a header cell, including any nested headers?

My handsontable has headers that include checkboxes and select boxes. How can I access the headers to check the value of a select/checkbox inside the header cell? You can view an example in this JSFiddle (with nested headers - same as my project): http:/ ...

Stopping HTTP redirection in Angular 2

Attempting to simulate user login using Angular2 Http. Let's describe the situation below. There is a PHP application where users can log in through http://sample.com/login.php URL (a form exists with username and password input, users must fill in ...

New elements can be inserted at the rear of the queue while older elements are removed from the front of the queue

I'm new to JavaScript and currently working on a task involving queues. Here is the task description: Create a function called nextInLine that takes an array (arr) and a number (item) as parameters. The function should add the number to the end of ...

What is the process of using the split() method to extract specific text from a string in JavaScript?

Working with AngularJS and facing a requirement to extract a specific text from a scope value. Here's my scope value: $scope.myLogMsg = '1111 order is placed by Sukumar Ms(User)'; //output: by Sukumar Ms(User) Desired output: by Sukumar Ms ...

"Expand" Button following X buttons

Check out this JSFiddle for the code: $(document).ready(function(){ $( ".keywordsdiv" ).each(function(){ $(this).children(".keywords").eq(3).after('<a href="" id="playtrailershowmorebuttons">....Show More</a>');//add a uniq ...

The angular variable is being updated, but the tweet embed code surrounding it is not being refreshed

I've been working with Angular to loop through an array of tweet ids and display them on the page using Twitter's embed code. The issue I'm facing is that although the variable gets updated, the twitter embed remains static. Here's a gl ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

Secure HyperText Transfer Protocol prevents JavaScript from executing

My website's HTTPS version is having trouble loading JavaScript. All scripts are hosted on the same server. I've attempted: <script type="text/javascript" src="https://server.tld/js/jquery.js"> <script type="text/javascript" src="//ser ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Expanding Grid Container in Material UI to Fill Parent Height and Width

Challenge I'm struggling to figure out how to make a Grid container element expand to the height and width of its parent element without directly setting the dimensions using inline styles or utilizing the makeStyles/useStyles hook for styling. I&ap ...