Angular 4 file upload verification: Ensuring safe and secure uploads

Is there a recommended method to validate the file type when uploading a file in an Angular 4 form? Are there any simple ways to accomplish this task?

Answer №1

A client-side validation feature is available.

Here is a simple illustration:

 upload(event: any) {
        let files = event.target.files;
        //checking the validity of the file
        if (!this.validateFile(files[0].name)) {
            console.log('The selected file format is not supported');
            return false;
        }

        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));
        this._service.uploadFile(fData).subscribe(
            response => console.log(response),
            error => console.log(error)
        )
    }

Validation process:

validateFile(name: String) {
    var ext = name.substring(name.lastIndexOf('.') + 1);
    if (ext.toLowerCase() == 'war') {
        return true;
    }
    else {
        return false;
    }
}

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 Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Creating an interface in Dart: Step-by-step guide to defining interfaces similar to TypeScript

Coming from a Typescript background, I used to define object interfaces like this: export interface Locale { login: { title: string; actions: { submit: string; forgot: string; } } } However, in Dart, interfaces are implicit an ...

Issue encountered when working with interface and Observable during the http parsing process

Visual Studio File Structure Error app(folder) -->employee-list(folder) -->employee-list.component.html -->employee-list.component.ts -->app.component.html -->app.component.ts -->app.module.ts -->employee.json ...

Contact creation not working on non-HubSpot form popups

I'm currently experiencing an issue with my website that has non-Hubspot forms. We have successfully integrated the tracking code to generate cookies for users, track their sessions, and enable the non-Hubspot forms. However, we are facing a problem s ...

What is the best way to verify both a null value and a length simultaneously within a template condition?

There is a data that can be null or an empty array, but the template should still be rendered if leaseApDto is not null or has a length greater than 0. I attempted to use the condition model.leaseApDto !== null || model.leaseApDto.length !=== 0, but they ...

Learn how to set up a class using TypeScript decorators

Is there a way to automatically initialize a class when a specific decorator is present above the class? For example: @apiController export class usersControllers extends lib.baseClasses.apiControllerBase().apiController { @lib.decorators.routesRegist ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Detecting when Angular2 input values change

Here is the updated code snippet: I am attempting to modify an input field and then submit the form. However, when I retrieve the form data using server-side code, the input has not been updated. <form id="cardsForm" method="post"> <inpu ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

In Typescript, which kind of event is suitable for MouseEvent<HTMLDivElement>?

My goal is to close the modal when clicking outside the div element. Take a look at my code below. // The onClose function is a setState(false) function. import { useRef, useEffect } from 'hooks' import { MouseEvent } from 'react' imp ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

`Inconsistent copying behavior across Chrome and Mozilla browsers for TypeScript`

I am facing an issue with copying the content of a textarea component to the clipboard. I have noticed that there are two different outcomes when running the code on Mozilla browser and Chrome: Below is my TypeScript code: 'HTML': <button ( ...

Change the router outlet to the currently selected tab

We are in the process of conceptualizing a cutting-edge angular 7 application featuring material design (md-tabs) with multiple tabs. Our goal is to enable dynamic tab creation, with each tab representing the content of a specific route. The home page sh ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

Error: Unable to access the property 'fn' of an undefined object in electron version 2 using Angular 6

I am currently utilizing Angular 6.0.3 and electronjs 2.0.2 with the package.json configuration shown below: { "name": "test", "version": "1.0.0", "license": "MIT", "main": "electron-main.js", "author": { "name": "Moh ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Unable to break down the property 'desks' of '(0 , _react.useContext)(...)' due to its undefined nature

Trying to mock DeskContext to include desks and checkIfUserPresent when calling useContext is causing an error to occur: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined TypeError: Cannot destruct ...

Navigating through Angular to access a component and establishing a data binding

I am looking for the best way to transition from one component to another while passing data along with it. Below is an example of how I currently achieve this: this.router.navigate(['some-component', { name: 'Some Name' }]); In Some ...

Avoid the need for props when implementing a component with a higher order component

Running into an issue with HOC and typescript. The compiler is asking for a value that is received from the HOC. Here's the component using the HOC: function Coupon(props: WithAlertProps): JSX.Element { return <p>test {props.error}</p> } ...