Converting base64 to binary string during file upload in Angular

Upon receiving data from a file upload, it appears in the following format:

data:application/pdf;base64,JVBERi0xLjcNCiW1tbW1D...

To include this file upload data along with other parameters, I need to convert it to a string binary. For example:

   var arraytosend = [{"id" : 0111,
  "file" : binary data here}]

Despite my attempts, I have been unsuccessful in converting the base64 data to binary.

Answer №1

If you need to convert a data URI to a Blob, there is a handy function available in this code snippet that can help you achieve this.

function convertDataURItoBlob(dataURI) {
  // Converting base64 or URL-encoded data component to binary data
  var byteString;
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
  else
      byteString = unescape(dataURI.split(',')[1]);

  // Extracting the MIME type
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // Writing string bytes to a typed array
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ia], {type:mimeString});
}

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

Using TypeScript to deserialize JSON into a Discriminated Union

Consider the following Typescript code snippet: class Excel { Password: string; Sheet: number; } class Csv { Separator: string; Encoding: string; } type FileType = Excel | Csv let input = '{"Separator": ",", "Encoding": "UTF-8"}&ap ...

The phenomenon of Angular 6 Caching with Http Interceptor: Observing how the Map operator alters the cached HttpResponse within the code

I have successfully implemented a cache in my Angular 6 app using an HttpInterceptor. It stores responses in memory and serves them with a TTL if they exist. However, I encountered a problem where the code responsible for making Http requests uses the map ...

The Angular component triggers a service which in turn triggers another service, and both services are required to perform actions based

I'm struggling to find the right way to phrase my question. Currently, I have an Angular component that needs to invoke a method on a service class. This method, in turn, needs to make an http call using my own http service and then perform some logi ...

What is the most effective way to determine the data type of a variable?

My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated! I am currently working on enabling strict type checking in an existing TypeScript project. One issue I'v ...

Exploring the Power of Observables in Angular 2: Chaining and

Hi there! I'm relatively new to Angular and still getting the hang of observables. While I'm pretty comfortable with promises, I'd like to dive deeper into using observables. Let me give you a quick rundown of what I've been working on ...

Type Assertion for Optional Values in TypeScript

Just confirming the proper way to handle situations like this. My current setup involves using Vue front-end with Typescript, sending data to an API via axios. I've defined reactive objects as follows: const payload = reactive({ name: '' ...

Using Angular: Fetch HTTP Data Once and Return as Observable in Service

My Goal: I need to retrieve data via HTTP only once and then share it across my entire application as properties. However, since HTTP requests can be slow, my app should continuously monitor these properties. The challenge is to ensure that the HTTP call i ...

Error Encountered: Anticipated 'styles' to consist of a series of string elements

I have attempted various solutions for this particular error message without any success. When launching my angular project using the angular cli via ng serve, everything runs smoothly with no errors. However, upon compiling it with webpack, I encounter th ...

Creating a variable within an ngFor loop

For my angular2 project, I need to display a matrix of workers and courses. Here's the current code I am using: <tr *ngFor="let worker of workers"> <td class="{{worker.fired ? 'fired-worker':''}}">{{worker.lastName ...

Two distinct datasets featuring differing Y-axis values along with their respective axis titles

I have been experimenting with nativescript+angular to create a unique chart that incorporates two different datasets - one for temperature and the other for pressure. Each dataset has its own Y-axis, one on the right and one on the left. I have successful ...

Resolving Modules: Using NPM to Install the Typescript Package Directly from Github

Recently, I decided to branch out and customize an existing npm package built in TypeScript to cater specifically to my unique requirements. I discovered that I could also install packages from GitHub branches using npm without any issues. However, after ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Accessing data from an object of type Request in NodeJS using Typescript

Is there a way for me to retrieve req.kauth.grant It is definitely populated because when I print req, I see this: kauth: { grant: Grant { access_token: [Token], refresh_token: undefined, id_token: undefined, token_type: undefi ...

When making use of useEffect along with unsubscribe, a warning regarding the missing return type on the function is triggered

I've implemented the following useEffect hook where I set a listener and then unsubscribe from it within a return statement. useEffect(() => { const listener = firebase.auth.onAuthStateChanged(authUser => { }) re ...

The Angular date picker is overly verbose in its data output regarding selected dates and requires optimization

Using Angular 5, I have integrated a specific npm package for handling dates import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime'; The problem arises when trying to send data to the server in this required format only ...

Navigating the "this" scope within a callback function while in strict mode

Having some trouble with error TS2683 when using webix(5.4.0) + typescript(3.1.1) in strict mode. ($$('DATE') as webix.ui.datepicker).attachEvent('onChange', function() { let val:any = this.getValue() // or let val = ... without ...

Dealing with multiple queryParams in Angular2: Best practices

Need help implementing a filtering mechanism in my new Angular2 app. Looking to filter a list of entries in an array based on around 20 properties. I've set up filters in one component and a list component as a child that is routed to. Initially, pas ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

A guide on implementing a return function in Typescript with Knockout

Seeking assistance with translating a JavaScript function to Typescript, which involves the use of knockout objects as entry parameters. Here are the TypeScript imports I am utilizing: import $ = require("jquery"); import ko = require("knockout"); Belo ...

JavaScript 2 add or remove a class to the keyboard when opening or closing

As I work on developing an app in Ionic 2, I am facing a challenge where the background image needs to change when the keyboard is opened and closed in an input field. <ion-content padding class="bg_gogreen"> <ion-list> <ion-item class=" ...