Retrieve the file from the input field

I have a requirement to retrieve an xls file and convert its content into json format. Currently, I am able to achieve this by specifying the file path directly in my code like below:

    var url = "D:/ionic/Docs/Test.xlsx";

However, I now need to allow users to select the file using an HTML input tag and then assign the selected file path to the var url. How can this be accomplished?

Home.html

<input type="file" accept="all/*" [(ngModel)]="getfile" (change)="onFileSelected($event)" id="fileInput"/>

Home.ts code:

onFileSelected()
  {
    var url = //what do I do here ;

Answer №1

Due to security measures, web browsers are unable to access the File System.

Therefore, it is not recommended to spend time attempting to do so.

However, you can still retrieve file data using the following method:

HTML

<input type="file" (change)="onFileSelected($event)" accept="all/*"/>

TS

    onFileSelected(event) {

        let file = event.target.files[0];  

        let reader = new FileReader();

        reader.onload = (e: any) => {
           let fileData = e.target.result;
           console.log(fileData);
        };
       reader.readAsDataURL(file);
}

View a working example here

Answer №2

const selectedFileName: string = '' ;
onSelectFile(event){
  let chosenFile = event.target.files[0];        
  this.selectedFileName= chosenFile.name;
}

The file you select will be stored in the selectedFileName variable.

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

Capturing and uploading pictures in Ionic-Angular.js: no images available for sending to server

After successfully utilizing a custom directive to upload images to my server using Angular.js, I ventured into implementing the camera functionality from Cordova. However, when attempting to connect the two processes, the images sent to the server are sto ...

Restricting the types within a generic union type in TypeScript

//Custom declaration: interface TickListFilter { type: "tickList"; value: string; } interface ColorFilter { type: "color" value: ColorValueType } type FilterType = TickListFilter | ColorFilter; ... updateValue = (filte ...

What is the best way to send my Array containing Objects to the reducer using dispatch in redux?

I'm currently facing an issue where I can only pass one array item at a time through my dispatch, but I need to pass the entire array of objects. Despite having everything set up with a single array item and being able to map and display the data in t ...

What is the best way to employ document.addEventListener in TypeScript?

I am currently learning Ionic v2 and I am using document.addEventListener, but I am encountering errors as shown below: > [11:10:21] ionic-app-scripts 0.0.47 [11:10:21] build dev started ... [11:10:21] clean started ... [11:10:21] clean finished in ...

Fixing the issue of "ng build --prod --deploy-url="/wp-content/themes/{name_theme}/dist/" not functioning correctly

Currently, I am working on creating a template in Angular 7 for Wordpress. Locally, everything appears to be functioning correctly when accessed through http://localhost:4200. However, when I attempt to run the command ng build --prod --deploy-url="/wp-c ...

Using act() in React/Jest/MSW causes errors when waiting for a response

As I delve into learning how to unit test with React, my focus has shifted towards using TypeScript. Unfortunately, the course I am taking does not cover most errors related to TypeScript. In my testing journey, I have set up a simple testing function with ...

Having Ionic call the submit method within another method seems to be causing some issues

I have a submit method that posts data to the server when a submit button is clicked. It works fine when done manually, but I want to automate it so that it is triggered after input texts are filled without having to press the submit button every time. H ...

Filtering an array with radio buttons in Angular

I am working with a JSON list that contains various audio files categorized by genre, along with their corresponding URLs. export const musicList = [ { 'id': 0, 'catName': 'upload', 'audios': [ { ...

Angular uploading image via WCF service call

I have been facing an issue while trying to upload an image from my Angular frontend through wcf. The upload process is successful and I receive a success message, however, the saved image is not viewable in any image viewer or program. The code snippet u ...

What is the best way to guarantee that an object contains certain fields using Partial<>?

I am dealing with a function that accepts a parameter as shown below: const handleAccount = ( account: Partial<IAccountDocument>, ... ) => { ... } It is crucial that the interface for IAccountDocument cannot be modified to avoid requiring cer ...

Utilizing Sequelize to establish associations between tables based on non-primary key columns

Here is the code snippet: User.hasMany(UserMail, {foreignKey:'to_user_id', sourceKey:'id'}); User.hasMany(UserMail, {foreignKey:'from_user_id', sourceKey:'id'}); UserMail.belongsTo(User, {foreignKey: 'from_use ...

How can you prevent the reducer switch from expanding when using Redux?

How can I prevent the switch statement in my reducer from becoming too large when using Redux? I am working with Angular 5 and ng2-Redux. I am concerned about the size of the switch statement as I add more action types to the reducer. Currently, I am at ...

inject a dynamic loading icon within the choices of a datalist in an Angular application

<input list="dataUsers" formControlName="user" placeholder="Type the user name" class="form-control form-control-lg" type="text" (ngModelChange)="doSearch($event)"/> <datalist id=&q ...

Adjusting the line width and incorporating arrow points into AxesHelper in Three.js

I have successfully implemented axes using AxesHelper https://i.sstatic.net/gYCKW.png Currently, I am looking to enhance the width of the axes lines and incorporate arrow points. Since I am new to three.js, I could really use some guidance on how to ach ...

Using ion-icon inside a clickable ion-card while applying float: right does not render properly

I am facing an issue with a list of ion-cards that have clickable icons appearing when you hover over them. The problem is that due to the floating nature of the icons, they are not positioned correctly (as shown in the image below) and end up getting cove ...

What are the different ways to customize the appearance of embedded Power BI reports?

Recently, I developed a website that integrates PowerBI embedded features. For the mobile version of the site, I am working on adjusting the layout to center the reports with a margin-left style. Below are the configuration parameters I have set up: set ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

Implementing server-side validation with Angular 2 and the .NET Core Web API

The code snippet in my HTML is: <form novalidate [formGroup]="personForm" (ngSubmit)="onSubmit()" class="form-horizontal"> <div class="form-group" [ngClass]="{'has-error':!personForm.controls.username.valid && personForm.con ...