Angular 13 - Retrieve a file from ByteArray information

Upon receiving a byte[] file from the server containing the content of a file along with its name and content type, I have attempted to download the file using the following JavaScript code:

const link = document.createElement('a');
document.body.appendChild(link);
link.style.display = 'none';

const blobFile = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(blobFile);
link.href = url;
link.download = "test.txt";
link.click();
window.URL.revokeObjectURL(url);

Unfortunately, this method downloads a text file with binary content. How can I convert the binary data to the appropriate file type on the client side using JavaScript or Typescript? Thank you for your help!

Answer №1

If you want to save files in your web application, consider using the file-saver library

import { saveAs } from 'file-saver';

Create a new Blob object containing the file content:
const file = new Blob([content], {type: 'text/plain'});

Save the file using FileSaver.saveAs():
FileSaver.saveAs(file, "test.txt");

Answer №2

storeBytesAsFile(data, fileType) {
  var blob = new Blob([data],{type:fileType});
  var downloadLink = document.createElement('a');
  downloadLink.href = window.URL.createObjectURL(blob);
  downloadLink.download = "myFile";
  downloadLink.click();
}

Answer №3

 C# .NET:
 public byte[] DocumentContent { get; set; }

Angular: 
DocumentContent: ArrayBuffer;

TypeScript: 
var content = this.base64ToArrayBuffer(response.DocumentContent);
        var blob = new Blob([content], { type: response.ContentType });

base64ToArrayBuffer(base64: any): ArrayBuffer {
    var binaryString = window.atob(base64);
    var length = binaryString.length;
    var bytes = new Uint8Array(length);
    for (var index = 0; index < length; index++) {
      bytes[index] = binaryString.charCodeAt(index);
    }
    return bytes.buffer;
  }

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

Creating a URL using input fields with JavaScript or jQuery

I'm currently working on developing a form that acts as a URL builder using JavaScript or jQuery. The main concept behind this form is to take the user-input values from two fields, combine them with a preset URL structure, and display the resulting ...

ajax continues to repeatedly post old values

I am facing an issue with a form that auto submits and updates the page. Despite having a JavaScript function changing a button's value, AJAX is still posting the old value. AJAX $.ajax({ type: 'POST', url: this.act ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

The Angular Google Maps Module fails to initialize

After updating angular-google-maps to version 2.0.1 via bower and adding the required dependencies (bluebird, jquery, loadash), I noticed that my app works fine when I comment out google-maps. This suggests that the issue lies with angular-google-maps. He ...

Strategies for transferring data between controllers and configuration files in AngularJS

I'm attempting to pass a variable to the angular js config, Here is my JavaScript app: var app = angular.module('myApp', ['ngMaterial', 'sasrio.angular-material-sidenav', 'ui.router']); app.controller('ba ...

Adjusting the position of the target div using bootstrap

One of the links on my website looks like this: <a href="mywebsite/testing/#collapse416">Testing</a></li> When clicked, it opens an accordion on a page by targeting the div of the collapse of the bootstrap accordion. However, I noticed t ...

Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise? Consider the following code snippet: User.getAllUsers().then(function(users) { $scope.users = users; for (var i = 0; i < users.length; i+ ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

How to activate service worker in Angular 4 web app

I'm a beginner in Angular 4 and currently working on developing an application using this framework. I want to incorporate offline capabilities into my app using a service worker. npm i @angular/service-worker --S Unfortunately, the above package is ...

When using $.ajax, an Object Object is returned

Encountering an error from the alert in the error function, with additional console.logs for debugging purposes. (Specifically tracking it entering into the error function) $( document ).ready(function() { console.log( "ready!" ); $('#register' ...

Highlight and extract the text from ag-grid

I have integrated the Ag-grid into my project and encountered an issue where users are unable to select text within the grid. Is there a solution or workaround to enable text selection and copying from the grid without switching to a different plugin? I am ...

Tips for accessing touch events within the parent component's area in React Native

I implemented the code below in my React Native app to disable touch functionality on a specific child component. However, I encountered an issue where the touch event was not being detected within the area of the child component. How can I fix this prob ...

Incorporate an HTML file into a div element in Angular

I'm facing an issue while trying to embed a Hosted HTML page in my angular app. Despite following this guide and making necessary adjustments for Angular 7, the div appears blank. I referred to this article: Angular4 Load external html page in a div ...

Discovering the HTTP status code from RNWebView

Currently, I am developing a React-Native/TypeScript application for both iOS and Android platforms. Upon completion of loading the webpage using RNWebView, it has become necessary for me to retrieve the HTTP response code. Since NavState does not provid ...

Where can the body of this function be located in Typescript and do the generics serve a practical purpose?

While perusing the documentation for Angular's "AsyncPipe", I found myself at a standstill on line 26, where the 'resolve' function is invoked: this.resolve !('hi there!'); I have some questions on my mind: (A) Where is the impl ...

I encountered an issue with my shopping cart while using ReactJS

this is the App.js file import React from "react"; import ListProduct from "./listProduct"; import ListOrder from "./listOrder"; import pizza from "./pizza.jpg"; import './style.css' import { Container,Row,Col,Button } from 'react-boo ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

Experiencing a Problem with Vue Form Input Bindings when Using Conditional Binding

Could someone provide assistance with adding a condition to this Binding that outputs different bindings depending on the number of commas in the input? <p>{{ target}}</p> <input v-model="target" placeholder="Enter Your Target ...

What is the correct way to add properties to an interface in TypeScript?

I have experience with styled-components "themes" and how they work by defining custom theme properties for TypeScript autocompletion within styled components. The process involves extending the DefaultTheme interface with our custom theme properties like ...