Malformed instance outputting from the constructor of Angular/Ionic File object

In a new project using Angular 4, you can easily create a simple text File object by following the constructor:

const textfile = new File (['abcd'], 'text.txt')
console.log(textfile)

When looking at the console output in VSCode, the expected result is shown:

File(13) {name: "text.txt", lastModified: 1520684955392, lastModifiedDate: Sat Mar 10 2018 13:29:15 GMT+0100 (Standard romance time…, webkitRelativePath: "", size: 13, …}
    lastModified:1520684955392
    lastModifiedDate:Sat Mar 10 2018 13:29:15 GMT+0100 {}
    name:"text.txt"
    size:13
    type:"text/plain"
    webkitRelativePath:""
    __proto__:File {name: <accessor>, lastModified: <accessor>, lastModifiedDate: <accessor>, …}

However, when the same code is executed on a fresh Ionic 3 project, it outputs incorrect properties for the File interface ("name" contains an Array with text content, there is no "name" property, "localURL" holds the file name, and "start," "size," and "end" properties are all 0).

File {name: Array(1), localURL: "text.txt", type: null, lastModified: null, lastModifiedDate: null, …}
end:0
lastModified:null
lastModifiedDate:null
localURL:"text.txt"
name:Array(1) ["text"]
size:0
start:0
type:null
__proto__:Object {slice: , constructor: }

I have tried to simplify my inquiry as much as possible, testing on different devices and verifying Angular and Ionic stable versions. I deployed this project locally in the browser to eliminate any potential device or emulator issues.

I am left wondering if this discrepancy is intentional behavior, a bug within Ionic's Angular implementation, or a misunderstanding of how to utilize this feature.

EDIT:

In response to Reed's comment:

Several suggestions have been made to work around the issue by bypassing Ionic and coding directly in Angular. Unfortunately, at that time, Ionic's documentation and resources did not provide a viable solution.

For me, Ionic seemed to add unnecessary complexity (JS -> TS -> Angular -> cordova/capacitor -> Ionic) onto an already heavy stack.

The solution to my specific problem was to remove Ionic from the equation and streamline the process. This approach may vary depending on individual needs.

For more details, refer to the comments section of this post.

Answer №1

Here's a solution that worked for me on Android too

convertBlobToFile() {
   this.convertBlobToFile(**base64**, 'Filename.xml').then(
   (file: File) => {
      const dataObj: FormData = new FormData();
      dataObj.append('file', file, 'Filename.xml');

      /***
        Additional code can follow here
      **/
   })
}  

async convertBlobToFile(dataUrl: string, fileName: string): Promise<File> {
   const response: Response = await fetch(dataUrl);
   const blobData: Blob = await response.blob();
   return this.createFileFromBlob(blobData, fileName, new Date());
}

createFileFromBlob(theBlob: Blob, fileName: string, dateGenerated: Date): File {
    const b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = dateGenerated;
    b.name = fileName;

    //Cast to a File() type
    return <File>b;
}

This solution might be useful to someone!

Answer №2

Check out this example -

let content = [];
let blobFile = new Blob(['efgh'], { type: 'text/plain' });
content.push(blobFile);  
const txtfile = new File(content, 'file.txt', {
  type: 'text/plain',
})
console.log(txtfile);

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

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...

Error message: TypeScript indicates that the specified column in the postgres database does not exist

Using pg library with TypeScript for querying Postgres, I have constructed a db class as follows: import { Pool } from 'pg'; const pool = new Pool({ host: process.env.PG_HOST, port: parseInt(process.env.PG_PORT), user: process.env.PG ...

Utilizing the Angular formArrayName directive in form elements

The Angular official documentation provides the following code example: @Component({ template: ` <form [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> ...

Combining Angular 2 and Symfony 3 for seamless integration

I am currently working on integrating Angular 2 with Symfony 3. After using npm to install node modules, I encountered an issue linking them from my base view base.html.twig. Despite adding scripts, none of them seem to be working or appearing in the page& ...

Disabling the ESC key from clearing input fields in Bootstrap-5: A step-by-step guide

I have come across this code snippet for a search field: <form class="container" role="search"> <div class="row"> <div class="col-12"> <input name="searchItem" #search ...

Remove any extra spaces at the end of a copied number when using Angular

Is there a way to automatically remove spaces at the end of a 10-digit number when it is copied from another source (like email or Word documents) and pasted into the search bar? Currently, this function only works when we press enter. I would like for bl ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

Error 503: NPM Registry Unavailability

I encountered an issue while trying to compile my angular app that resulted in the error message "npm ERR! 503 No healthy backends: gulp-cli@latest" Here is the stack trace of the error: npm ERR! code E503 npm ERR! 503 No healthy backends: gulp-cli@late ...

Potential undefined objects in Angular unit testing

While working on unit testing, I encountered the following error: 'Object is possibly 'undefined'' it('should set the dataSource filter to the provided argument', () => { component.applyFilter('filterValue') ...

Error: Unable to access properties from an undefined source while trying to read 'reRenderOnLangChange'

I encountered an issue in my Angular project where my unit tests are failing with the following error message: TypeError: Cannot read properties of undefined (reading 'reRenderOnLangChange') at shouldListenToLangChanges (node_modules/@ngneat/tr ...

Guide to importing JavaScript in an npm package using TypeScript and JavaScript

I recently downloaded a library that includes both Typescript and its corresponding javascript version. Despite trying to declare import Library from "@scope/library", my application is only able to access the Typescript version, even after adding the .js ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Revamp the way slides are showcased in swiper.js

I implemented a swiper js slider in my project and I am wondering if it is possible to change the default slide that is shown. For example, my slides are named slide1, slide2, slide3, etc. Currently, swiper js is displaying slide 1 by default, but I would ...

What methods can I use to bypass CORS in Angular 9?

Upon attempting to access the specified URL, I encountered this error message: Access to XMLHttpRequest at 'http://localhost:40000/api/summaryCount/failed-requests' from origin 'http://localhost:3000' has been blocked by CORS policy: ...

Struggling to retrieve an Object from an HTMLSelectElement within an Angular project

Can you help me with this code snippet: <select #categorySelect (change)="goToCategory.emit(categorySelect.value)" style="..."> <option selected hidden>All</option> <option [ngValue]="categ ...

Managing copious amounts of data in an Angular project using a Restful API

After developing my own Restful API within a Laravel project, I am faced with the challenge of efficiently managing large amounts of data returned by the API in order to display it on an Angular front-end project. For instance, when using the GET method t ...

What are some best practices for integrating ES2020 into an Angular project?

Below is the content of my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap&q ...

Is it possible to perform remote file upload using Selenium in TypeScript?

Is there a specific way to manage remote file uploads using selenium-webdriver in typescript? Here is code that functions in javascript for this purpose: import remote from 'selenium-webdriver/remote'; // import * as remote from 'selenium- ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

What is the best way to assign values to mat-select in Angular using the component class?

I am currently delving into the world of Angular and experimenting with my own Angular code. HTML Component <mat-form-field class="select-country-component"> <mat-label>Select Country</mat-label> <mat ...