How to send files to the browser without triggering download using AngularJS and WebAPI?

I'm tearing my hair out over this issue.

Currently, I have a GET request set up through Angular:

x.DeliverFile = function(fileId) {
  $http({
    method: "GET",
    url: myBase + "Services/DeliverFile?FileID=" + fileId,
    headers: myHeaders
  }).success(function(data, status, headers, config) {
    console.log(data);
  });
};

On the WEB API side of things:

If fileinfo.Exists Then
  Dim result As New HttpResponseMessage(HttpStatusCode.OK)
  With result
    .Content = New StreamContent(New FileStream(fileinfo.FullName, FileMode.Open, FileAccess.Read))
    .Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
    .Content.Headers.ContentDisposition.FileName = fileinfo.Name
    .Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/octet-stream")

  End With
  Return result

  Else
    Return Request.CreateResponse(HttpStatusCode.NotFound)
End If

I've implemented similar functionality using httphandlers multiple times in the past, but seem to be missing something crucial with web api.

While I can see the bytes coming in through console.log(data);

I just can't quite grasp how to prompt the browser to download the file.

I came across this post: Download file from an ASP.NET Web API method using AngularJS

Despite the suggested solution, I'm struggling to fully accept it as the definitive answer, believing there must be a more universally compatible way to trigger downloads across different browsers.

Answer №1

To achieve this functionality, it is recommended to utilize a library such as FileSaver.js. Once you have integrated FileSaver.js, you can implement the following code snippet:

x.DeliverFile = function(fileId) {
  $http({
    method: "GET",
    url: myBase + "Services/DeliverFile?FileID=" + fileId,
    headers: myHeaders
  }).success(function(data, status, headers, config) {
    var blob = new Blob(data, {type: "text/plain;charset=utf-8"});
    saveAs(blob, "fileName.txt");
  });
};

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

Activating and deactivating event capturing in Vue.js

Incorporating Vue.js into my project has been a game-changer. One interesting aspect is the event listener's third option, known as capture. For instance: element.addEventListener("click", function(){}, true); I'm curious if it's ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

What could be the reason for my jQuery script not functioning properly?

<script> var currentLevel = 0; $(document).ready(function(){ $("#tolevel_" + (currentLevel+1) ).click(function(){ $("#level_" + currentLevel).hide(500,'swing', function(){ $("#level ...

Accessing deeply nested objects from props

After pulling an object from my MongoDB database with Redux and passing it as props to a component, I am facing an issue where I can see the object in the console log but cannot access any information within the object. My objective is to extract specific ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...

Which is the preferable option for creating a circular daily planner: canvas or SVG?

As a novice programmer delving into the world of coding (or at least hoping to), I have a question regarding graphic tools in html5 for my latest project. My goal is to create a planner app using electron, with the unique twist that the planner form sho ...

The filter feature does not function properly when used with an ng-option generated from an array, but it performs effectively with static

<select ng-model="myOption" class= "form-control" ng-options="value.status for value in records | unique:'status'"> </select> Displays only one record when filtered with the criteria below <tr ng-repeat="data in records | filter: ...

Dealing with JQuery and CSS issues on Internet Explorer

Recently, I've been working on a code snippet to maximize a video panel upon page load or resize. Utilizing JQuery 1.4.4, the implementation has been smooth sailing on Chrome, Firefox, and Safari. Drawing inspiration from various online resources, I&a ...

Utilize the same variable within a React functional component across multiple components

Within a React functional component, I am utilizing the following constant: const superHeroPowers = [ { name: 'Superman', status: superManPowerList }, { name: 'Batman', status: batmanPowerList }, { name: 'Wonder Woman&a ...

Validating ReactJS properties

Transitioning from ReactJs to React-Native, I came across this function structure in a react-native button code by Facebook: class Button extends React.Component<{ title: string, onPress: () => any, color?: ?string, hasTVPreferredFocus?: ?bo ...

What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use ...

Arranging null values and numbers to imitate the behavior of the tabindex HTML attribute

Currently, I am facing a rather unusual issue with JavaScript sorting. As I delved into the complex world of sorting, I found myself in need of some guidance: My goal is to replicate the functionality of the tabindex HTML attribute, which alters the order ...

Exploring Relative Rotations in Three.js

I currently have a scenario where I have a THREE.Scene containing two meshes, namely meshA and meshB. Both of these meshes have been rotated differently. My objective is to take meshB out of the scene and attach it as a child of meshA, while maintaining it ...

What is the method for retrieving authorization response headers in a jQuery AJAX success callback?

While working on setting up encrypted username and password authorization on the front end, I encountered an issue where I am receiving a bearer authorization response header from the server. Interestingly, in Safari, I am able to retrieve this response he ...

Is there a way to convert an array into a single comma-separated value using parameters?

Is there a way to parameterize an array as a single name-value pair that is comma separated? I have tried using jQuery $.param, but it creates a parameter for each value in the array instead of just one. Unfortunately, it seems that there is no option or s ...

Issue with jQuery select box (roblaplaca) and its custom scroll bar functionality not functioning as expected

Recently, I implemented the custom select box script from . This script allows for two select boxes, where the second one updates dynamically using AJAX when there is a change in the first select box. Below is a sample of the HTML code: <option>One& ...