What is the process for downloading a file from a webapi on Internet Explorer with an angular post request?

I have encountered an issue with my code while using angularjs http post to download a file from the Web Api. The code works perfectly fine in Google Chrome and Firefox, however it fails in Internet Explorer. Here is the code snippet:

$scope.CallApi = function () {
        $http({
            url: some url,
            dataType: 'json',
            method: 'POST',
            data: null,
            responseType: 'arraybuffer',    

        }).success(function (responsedata, status, xhr) {           
            var file = xhr('Content-Disposition');
            console.log(file); 
            var filename = file.substr(21, 7);
            $scope.value = responsedata;
            var fileName = filename;
            var blob = new Blob([responsedata], { type: "application/octet-stream" });
            var url = URL.createObjectURL(blob);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            a.href = url;
           a.download = fileName;        

        }).error(function (error) {
                alert("Error Found" + " : " + error);
            });
    };

The above code does not work in Internet Explorer. I prefer not to use FileSaver.js extension. Is there any alternative way to download the file from api in Internet Explorer? Attached below is the screen shot of the error message I am receiving in Internet Explorer: https://i.sstatic.net/CF1Ti.png Thank you in advance.

Answer №1

Looking for a method to download in Internet Explorer?

  if (window.navigator.msSaveOrOpenBlob){
      // base64 string
      var base64String = response;
      // decode base64 string, remove space for IE compatibility
      var newString = base64String.replace(/\s/g, '');
      var binaryData = atob(newString);
      // get length of binary data
      var dataSize = binaryData.length;
      // create ArrayBuffer with binary data length
      var buffer = new ArrayBuffer(dataSize);
      // create 8-bit Array
      var view = new Uint8Array(buffer);

      // save unicode of binary data into 8-bit Array
      for (var i = 0; i < dataSize; i++) {
        view[i] = binaryData.charCodeAt(i);
      }

      // create the blob object with content-type "application/csv"               
      var blobObject = new Blob( [view], { type: mimeType });
      window.navigator.msSaveOrOpenBlob(blobObject, "Name your file here");
}

In this code snippet, replace 'mimeType' with application/octet-stream and 'response' with your actual base64 string.

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

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

What is the method for breaking down a React useState hook into separate variables within a namespace?

Personally, I like to group React props into namespaces for better organization. When using the useState hook, I follow this approach. function MyComponent() { const [todoCount, setTodoCount] = useState(100); const [doneCount, setDoneCount] = useSta ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

Exploring the capabilities of the innovative Node's EventTarget class alongside ES6 modules

Exploring the new DOM-compatible EventTarget class introduced in Node.js 14.7.0 has caught my interest. I've noticed that I can only utilize it within a CommonJS module, and not an ES6 module. Here's an example: Executing node --expose-internal ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...

Utilizing Axios to Send Form Data in ReactJS

I encountered an issue with the post method using Axios. When I submit it, an error is displayed: Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87) Oddly enough, if I use ...

Converting form fields with varying sets of data into JSON using JavaScript

I am currently working on a form that contains multiple rows with three fields each - a hidden id, code, and exchange. <form id="form_in_question"> <table> <tr> <td>0</td> <td> ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

Using HTML Select field to make ajax calls to web services

When working with modals that contain forms to create objects for database storage, there is a Select field included. This is the code snippet for the Select field: <div class="form-group" id=existingUser> <label>Username</label> < ...

My variable from subscribe is inaccessible to Angular2's NgIf

My goal is to display a spinner on my application while the data is being loaded. To achieve this, I set a variable named IsBusy to True before making the service call, and once the call is complete, I set IsBusy to false. However, I am facing an issue wh ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

issue with horizontal scrolling in react menu component

**Hi there, I'm encountering an issue with react-horizontal-scrolling-menu. When scrolling, it moves to the right excessively and causes other elements to disappear. Additionally, adding overflowX: 'scroll' to the BOX doesn't activate t ...

Tips for sending a form without reloading the page in node.js and ejs

<form action="" method="post"> <div class="bottom_wrapper clearfix"> <div class="message_input_wrapper" id="eventForm"> <input class="message_input" name="msg" placeholder="Type your message here..." /> </div ...

Retrieve both positive and negative reviews using the Steam API

I'm trying to calculate the percentage of positive reviews, but I haven't been able to find the necessary data. I've been using this endpoint to retrieve game information: "", but it only provides the total number of reviews. I am aware of a ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

I am having trouble reaching the _groups attribute in angular/d3js

I am encountering an issue when trying to access the "_groups" property in my code: function getMouseDate(scale){ var groupElement = d3.select("#group")._groups[0][0] var xCoordinate = scale.invert(d3.mouse(groupElement)[0]); co ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...