Utilizing Angular to handle all your file uploading, storing, and downloading needs with base

I am currently working with Angular and attempting to upload a file to be stored in the database, and then download the file. I am utilizing base64 encoding/decoding for this process. It appears to be functioning correctly, however, when I try to open the downloaded file using Windows' default image viewer, an error message pops up stating "It looks like we don't support this format." Despite this message, the file isn't empty as its size is greater than zero. I suspect that my variable 'decode' showing up as type [object ArrayBuffer] in the debugger rather than a string might be the issue.

//The code used to read the file (for example: a jpeg file):

   let fileReader = new FileReader();

    // Callback function for when the filereader's onload event fires (readAsBinaryString() below)
    fileReader.onload = async (e) => {

      // Base64 encode the file contents
      let encoded = btoa(fileReader.result as string);
      // Pass the encoded file content, type, and name to the API

      //Store the file (i.e. encoded) in the database
  // Note: I compared this value to the value retrieved from the database below and they match
    }

    // Now read the file contents. This is an asynchronous operation and the onload callback will be triggered upon completion
    fileReader.readAsBinaryString(documentName);

//Retrieve it let documentName = 'test.jpg'; let encodedDocument = xxx; //the encoded string obtained from the database, matching what was saved previously let documentFormat = 'image/jpeg'; let decoded = atob(encodedDocument);

    //Download it
    const blob = new Blob([decoded], { type: documentFormat });
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = documentName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();

Answer №1

After some trial and error, I finally solved the problem. It seems like atob function was not doing its job correctly. The solution was to utilize this specific URL for downloading purposes: let downloadUrl = 'data:' + docFormat + ';charset=utf-8;base64,' + encodedDoc;

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

Setting Angular FormControl value to null within a service

My Angular form is reactive and collects mobile numbers along with other details. Here is the code snippet: component.html <form [formGroup]="contactDetailsForm"> <ngx-intl-tel-input [cssClass]="'ngxIntlInputBorder'&quo ...

The constant increase in page header number leading to minor interruptions during page scrolling

On my website, I have a dynamic page header that shows the number of comments a user has scrolled through. You can see this feature in action here: However, there seems to be a slight jitter on the screen every time the comment counter updates... To disp ...

Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; interface WindowSize { width?: number; height? ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

Utilizing SCSS variables

Currently, I am in the process of developing an Angular 4 application using angular-cli and have encountered a minor issue. I am attempting to create a component that has the ability to dynamically load styling. The ComponentX component needs to utilize a ...

The form data consistently replaces existing values with each new entry added

I am struggling to persist all the form values that are entered in my component using local storage. Despite setting and pushing the form values, I noticed that each time I push the data, it replaces the previously entered form data. My goal is to retain a ...

Tips for utilizing callback function in Angular 4

I previously used the Google API to obtain a current address and now I want to incorporate a callback function in this process using Angular 4. How can I go about implementing it? let geocoder = new google.maps.Geocoder(); geocoder.geocode({ &ap ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

Having difficulty installing node-sass in an Angular project

Having downloaded a repository from an existing Angular project, I proceeded to run sudo npm install within the project. While all packages were successfully installed, the node-sass package continued to cause issues. Upon completion of the installation ...

TypeScript's HashSet Implementation

I'm working on a simple TypeScript task where I need to extract unique strings from a map, as discussed in this post. Here's the code snippet I'm using: let myData = new Array<string>(); for (let myObj of this.getAllData()) { let ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Set the component variable to hold the output of an asynchronous method within a service

As I work on developing an application, I aim to keep my component code concise and devoid of unnecessary clutter. To achieve this, I plan to offload complex logic into a service which will then be injected into the component. Suppose my component includes ...

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

Keep an eye on the output of Firebase database in Angular 2

Just starting out in angular, so please be patient :) Using Angular 2 (version 1.0.4), Angular CLI, and NodeJs 7.9. I've been trying to create a centralized service that checks if a user is logged in, retrieves their data, and sends it back for the ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...