Can a blob file be transformed into base64Data using Javascript specifically in Ionic and Angular frameworks?

https://i.stack.imgur.com/3aMyx.png[

async FileZip() {
    const code = await fetch("./assets/input.txt")
    var blob = await downloadZip([code]).blob()
     console.log(blob);

 
   function blobToBase64(blob: Blob): Observable<string> {
      return new Observable<string>(observer => {
          const reader = new FileReader();
         reader.onerror = observer.error;
          reader.onabort = observer.error;
          reader.onload = () =>                     observer.next(reader.result as string);
          reader.onloadend = observer.complete;


    FileSharer.share({
      filename: "input.zip",
      base64Data: //base64datawillbehere ,
      contentType: 'application/zip'
    });
    reader.readAsDataURL(blob);
  })

I am brand new to the world of Ionic and App Development. I've successfully compressed a text file into a zip blob file using client-zip library. After utilizing downloadZip(), I obtained a zip blob file similar to this example. Now, my goal is to share this file as a zip file using Capacitor Filesharer. However, it appears that in order to use this Filesharer plugin, I need to convert the blob zip file into base64 data. Could someone provide guidance on how to achieve this? Is it even possible? Please excuse any ignorance in my question, as I'm still learning the ropes of JavaScript.

Answer №1

Here is a useful function that you should consider implementing:

function convertBlobToBase64(blob: Blob): Observable<string> {
    return new Observable<string>(observer => {
        const reader = new FileReader();
        reader.onerror = observer.error;
        reader.onabort = observer.error;
        reader.onload = () => observer.next(reader.result as string);
        reader.onloadend = observer.complete;
        reader.readAsDataURL(blob);
    })
}

Answer №2

Consider making the following adjustments to your code: (keeping the previous answer unchanged could help others who want to utilize the Observable strategy, unlike your scenario where using Promise is recommended)

ngOnInit(): void {
  this.fileZip();
}

private blobToBase64(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = reject;
    reader.onabort = reject;
    reader.onload = () => resolve(reader.result as string);
    reader.readAsDataURL(blob);
  })
}

private async fileZip(): Promise<void> {
  const code = await fetch("./assets/input.txt")
  const blob = await downloadZip([code]).blob();
  const base64Data = await this.blobToBase64(blob);
  await FileSharer.share({
    filename: "input.zip",
    base64Data: base64Data,
    contentType: "application/zip",
  })
}

Answer №3

Here is a code snippet that might help you:

functionZipFiles() {
constfiles = awaitfetch("./data/files.txt");
varzipFile = awaitcreateZip(files);
console.log(zipFile);
varzipData = newBlob();
zipData.readAsDataURL(zipFile); 
zipData.onloadend = ()=> {
constresult = zipData.resultasstring;
constencodedData = result.split(',')[1];
console.log(encodedData)
DownloadManager.downloadFile({
filename:"archive.zip",
data: encodedData,
type:'application/zip'
    });
  }
}

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

Align a button within an input field to be in line with a stacked label in

I'm currently facing some issues with Ionic because it's not placing my button where I want it to be: https://i.stack.imgur.com/qtUQJ.png My goal is to have the button on the same line as the input, similar to the clear-button. This is the cod ...

Exploring within the Angular submodule path

I am facing a challenge with nested modules having different URL prefixes. I want to navigate within one module without specifying the prefix, making it accessible regardless of the prefix. Here are the routes for my app.module: const APP_ROUTES: Routes ...

Identify the classification of unfamiliar items

Occasionally, you may find yourself in situations where you have to work with packages that were not designed with TypeScript in mind. For instance, I am currently using the two.js package in a React project with TypeScript strict mode enabled. It has been ...

Looking for a streamlined process to manage the development and publication of multiple versions of the React module using the "yarn/npm link" workflow

Currently, I am in the process of developing and releasing a module on npm that relies on the React library. As part of my workflow, I am utilizing yarn along with yarn link. The module has been created within a larger parent project, but now I am looking ...

What is the best way to retrieve Firebase data and assign it to a variable in React after using setState

Working with react and firebase real-time database for the first time has been quite challenging. I'm struggling to extract the data and insert it into a constant called items. It seems like the firebase code is asynchronous, which means it executes a ...

Firefox compatibility issue with Angular JS for downloading excel files

I've encountered an issue with my AngularJS code for downloading an Excel file. While it works smoothly in Chrome and Internet Explorer, it fails to function in Firefox. The server response isn't presenting any problems. Here's the code snip ...

Issues with finding your way

Whenever I am in the History.js file and click on a product list item to navigate to another page for more details and contact the seller, the issue arises. When I click on an item in History.js, nothing happens on that page. However, when I switch to Home ...

Extending Mongoose's capabilities with header files for the "plugin" feature, utilizing the .methods and .statics methods

My task is to develop Typescript header files for a script that enhances my Mongoose model using the .plugin method. The current signature in the Mongoose header files looks like this: export class Schema { // ... plugin(plugin: (schema: Schema, opt ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

Solving the challenge of handling multiple text inputs in Laravel Blade using Vue.js v-model within a @

Hello, I am encountering an issue with my Laravel application that displays posts and comments. The problem lies with the Vue v-model in the input text when using the @foreach directive in Blade. Each post is showing the comments input box, but when I ente ...

Where is the best location to store types/interfaces so that they can be accessed globally throughout the codebase?

I often find myself wondering about the best place to store types and interfaces related to a specific class in TypeScript. There are numerous of them used throughout the code base, and I would rather not constantly import them but have them available gl ...

Checking the validity of date inputs - microservice for timestamps

I'm encountering an issue while attempting to validate my date input. I've tried using moment js, but it seems there's a problem. The error message "date invalid" keeps popping up! Here is the code snippet: app.get("/api/timestamp/:date_s ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Issue with Angular 5 - Deselect all checkboxes not reflecting in the UI

I am currently working on integrating a reset button into a Reactive form in Angular 5. The reset functionality works flawlessly for all form fields, except for the dynamically created multiple checkboxes. Although it seems like the reset operation is hap ...

Using jQuery to scroll within a table

I am currently working on a project that involves displaying specific data rows. To achieve this, I have decided to use a table. For a better understanding, you can check out a table demo here. The issue I am facing is that whenever I change the selected ...

What causes the "undefined" error in Node.js when using a

Currently, I am utilizing the node-craigslist package for scraping listings from craigslist. However, I have encountered an issue when processing the results. client .search(options, '') .then((listings) => { listings.forEach((listing ...

Guide to deactivating the user interface in AngularJS until receiving a server response

Currently, I am in the process of developing a web application using AngularJS and Node.js (Express). During various interactions within the app, users will be required to communicate with the server. Depending on the response received, different actions ...

The error with removing the form field control in Angular 7 persists

I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure of the FormGroup: ngOnInit() { this.basicInfo ...