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

What steps can be taken to eliminate the 404 error when refreshing an Angular 8 Single Page Application (SPA) without using

In my single page application project, I am utilizing Angular 8. Upon uploading my published code to the IIS server without using hash(#) in routing, I encounter a 404 error when attempting to refresh the page. Can anyone provide assistance on how to res ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

Obtaining a variable from HTML and passing it to Node.js

Currently, I am utilizing express to handle form submissions. Within my HTML file, there are 20 inputs with unique ids such as address1, address2, address3, and so on. In my node js code, I access these input values using req.body.address1. Users have th ...

What is the best way to retrieve a nested data type?

I am working with an interface named IFoo interface IFoo { name: string; version: number; init: (arg1: string, arg2: number) => Promise<string[]>; } I am interested in the type of init. Is there a way to extract it so that I can use this i ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

Specifying data type in the fetch method

Screenshot depicting fetch function I'm currently working on a project using Next.js with Typescript and trying to retrieve data from a Notion database. I've encountered an error related to setting up the type for the database_id value. Can anyon ...

Having difficulty incorporating custom JavaScript files into a testing framework

I am facing a unique challenge while integrating the Page Object design pattern into my test suite using selenium-webdriver and node.js. The first page object, pageObject/admin/login/index.js, works seamlessly. It contains selectors and methods to fill ou ...

The state value is not preserved after redirecting to another page

For the past couple of days, I've been struggling with an issue and I can't seem to figure out what I'm doing wrong. My goal is to create a login page that redirects users to the dashboard after they log in. To maintain consistency acros ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

RecoilRoot from RecoilJS cannot be accessed within a ThreeJS Canvas

Looking for some guidance here. I'm relatively new to RecoilJS so if I'm overlooking something obvious, please point it out. I'm currently working on managing the state of 3D objects in a scene using RecoilJS Atoms. I have an atom set up to ...

Update the path dynamically in Next.js without the need to reload the page

Every time the user clicks on the continue button, a function is triggered. Within that function, I make the following call: push("/signup/page-2", undefined, { shallow: true }); All dynamic routes resembling /signup/[page].js that return <Component / ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

"Exploring the possibilities of customizing Material UI tabs and implementing a tabs scroller

I'm currently trying to customize the appearance of these MUI tabs, specifically the tab color and bottom border color. Despite my attempts using makeStyles and other methods, I haven't been able to achieve the desired result. Here is an example ...