Step-by-step guide on converting a file upload to a JavaScript object in Angular 11

I need to parse a JSON file into an object before sending it for validation in an API call. The current code is not working and the API requires an object.

<label class="form-label required" for="file">File</label>
<label
    class="button secondary wide required"
    for="file"
    (click)="inputFileTarget.click()"
>
    Select JSON file
</label>
<input
    id="inputFileTarget"
    #inputFileTarget
    type="file"
    class="hidden"
    accept=".json"
    formControlName="fileInput"
    (change)="onFileChange($event)"
/>

component:

    const formData = new FormData();
    formData.append('file', this.importForm.get('fileSource').value);
    this.wizard.next();
    this.validateUploadedTemplate(formData);

private validateUploadedTemplate(formData: any): void {
    this.templateUploadService.validate(formData)
    .subscribe(result => {
        console.log('result', result);
    })
}



[HttpPost]
    [ResponseType(typeof(Boolean))]
    [Route("validate-definition", Name = "ValidateAuditTemplate")]
    [RequiredActivity(RadarModuleKeys.EnhancedAudits, EnhancedAuditActivities.ManageEnhancedAudits)]
    public async Task<IHttpActionResult> ValidateAuditTemplate(TemplateDefinition template)
    {


        return Ok(await Task.FromResult(true));
    }

Answer №1

Simply attempting to ``access'' the file in that manner is not sufficient. Utilizing

this.importForm.get('fileSource').value
will yield a FileList.

interface FileList {
    readonly length: number;
    item(index: number): File | null;
    [index: number]: File;
}

Even if you designate

<input multiple="false" />
, a FileList with just one item will be returned.

If your goal is to obtain only one item, extract the initial item from FileList and apply FileReader to interpret the content.

An informative explanation can be found here: Read a file and parse its content

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

Is it possible to include images in code comments within the Visual Studio Code environment?

Can images be inserted into code comments in VS Code? Currently, I am involved in an angular project where adding descriptive comments is crucial. While explaining a login process using just text may not be as effective, incorporating an image could enhanc ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

Error encountered when upgrading to Material-UI v5 rc.0 with typescript

After updating my material-ui to version v5-rc.0, I decided to implement styled-components. However, as I was working on my Component.styles.ts file, I encountered an error: The inferred type of 'StyledStepper' cannot be named without a referen ...

Vue 3 is unable to detect any alterations made to an object that was created externally to the Vue component

I am working with a class called Character in a file named Character.ts /// This is called when server responds public setAttributeByType(type: StatsTypes, value: number): void { switch (type) { case StatsTypes.STRENGTH: ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code: const button = await this.page.$$eval('button', (elms: Element[], label: string) => { const el: Element = elms.find((el: Element) => el.textContent === l ...

There is no index signature in the type 'string | number | EnvType' that accepts a parameter of type 'string'

Can someone help me troubleshoot this issue with config[curr][targetEnv] ??? interface EnvType { dev: string; staging: string; production: string; } type Config = { [key: string]: number | string | EnvType; }; const config: Config = { network ...

Transform a promise-based function into an observable stream

I'm looking for advice on how to convert a piece of code that uses and returns a promise into an observable. Here is the original code snippet: export const uploadMultipleFilesToAzure = ( uploadData: Omit<UploadMultipleToAzure, 'id'> ...

Best practices for utilizing React.Provider in Typescript to manage and refresh user context

I'm currently trying to wrap my head around how Typescript is structured. However, my Typescript React web app is failing to build due to the following error: Type '({ user: { id: any; }; } | Dispatch<SetStateAction<{ user: { id: any; }; }& ...

Guide to TypeScript, RxJS, web development, and NodeJS: A comprehensive manual

Looking for recommendations on advanced web development books that focus on modern techniques. Digital resources are great, but there's something special about reading from a physical book. I don't need basic intros or overviews - consider me an ...

How can the output of a FormControl be converted into an instance of an interface?

When submitting a form contained within a FormGroup instance, I need to assign the filled values to an object created based on the interface schema. However, attempting to do this directly results in the following error: ERROR in src/app/modules/objec ...

Tips for showcasing information from a nested array and modifying data in an Angular application

I am in the process of developing a cutting-edge Angular application to monitor my fitness workouts at the gym. Enclosed within this array are the diverse exercise names, repetitions, sets, weights, and more that constitute each workout: workoutExercises ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

How to include extra data in Angular Firebase user creation using the createUserWithEmailAndPassword

Currently, I am working on implementing the Firebase createUserWithEmailAndPassword method. However, I would like to include an additional field named 'name' in Cloud Firestore. Below is a snippet of my code: auth.service.ts SignUp(email: string ...

Unlocking the Power of RxJS with Observable Sharing

Let's take a look at a function that contains the code below: private foo() { let obs: Observable<any> = this._http.get<number>('/foo') obs.subscribe(x=> { console.log("foo : " + x) }); this.blah(ob ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Angular trailing zero problem

There is a function that returns a number. Within this function, a string '1.10' is present, which is then converted to a number using the Number method. The output obtained is 1.1, but the desired output is 1.10. I have tried using methods lik ...

Performing an HTTP POST request in Angular 2

After starting my work with Angular 2 and TypeScript, everything was going great. However, I encountered an issue when working with a REST API (POST) where the console log displayed Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type ...