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

Redux ConnectedProps will always have a type of never

I am facing an issue while attempting to connect a component to my Redux store following the steps outlined in the official documentation guide. The props that are connected seem to be coming through as type never. Here is a snippet of my code: Type defi ...

Find the TypeScript data type of an array that may be empty

Struggling to determine the TypeScript type of data being passed into my React component. The data could either be related to cats or dogs: my-component.tsx: export const MyComponent = { props: { data: any; // Ideally looking to utilize the union type & ...

How can I create a universal "Add" button in Angular that can be used across all child components?

Currently, I am working on a straightforward application featuring a toolbar at the top of the screen. Within this toolbar, there is a + button designated for adding content. The functionality of this + button changes based on which component is currently ...

How to format dates when exporting Excel from Kendo Grid in Angular 2

When attempting to export data from the Kendo UI Grid for Angular, there seems to be an issue with formatting the date column. The actual date value is not being displayed correctly in the exported file. Below is a snippet of the code: <kendo-excelexpo ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...

Unable to modify the date input format in Angular when utilizing the input type date

I am currently working with angular 10 and bootstrap 4. I am trying to update the date format in an input field from (dd/mm/yyyy) to DD/MM/YYYY, but I am facing issues. Below is my angular code: <input type="date" id="controlKey" cl ...

Why am I encountering this issue? The "map" property does not appear to be available for the type "Observable<boolean>"

I have been working on an Angular project where I am utilizing an AuthGuard class to prevent unauthorized access to protected pages. Despite following an online course, I encountered the following issue: import { CanActivate, ActivatedRouteSnapshot, Router ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

React.Js custom form validation issue in Next.Js - troubleshooting required

My attempt at validating a form is causing some issues. After refreshing the page and clicking on the submit button, only the last input's error is generated instead of errors for every input according to the validation rules. Here is a screenshot o ...

Exploring the Angular lifecycle hooks for directives: AfterContent and AfterView

According to the Angular documentation, it is stated that AfterContent and AfterView lifecycle hooks are intended for components and not directives. Surprisingly, I have a directive that seems to be using them without any issues. What potential limitation ...

What could be causing issues with my Angular and Express.js Server-Sent Events implementation?

Objective: Implement Server-Sent Events in Angular App with Express Backend Issue: Client does not receive Server-Sent Events Backend Implementation router.get('/options/:a/:b/:c', async (req, res) => { console.log('options endpoint c ...

Using ngFormModel with Ionic 2

How can I properly bind ngFormModal in my Ionic 2 project? I am facing an issue while trying to import it on my page, resulting in the following error message: Uncaught (in promise): Template parse errors: Can't bind to 'ngFormModel' since ...

What could be causing the image to vanish when combining a condition with 'linear-gradient' as the value for 'background-image'?

If the variable effect is set to true, I want to display the linear-gradient effect, otherwise only show the image. picture = 'https://i.blogs.es/7c43cd/elon-musk-no-queria-ser-ceo-e-hizo-todo-lo-posible-para-evitarlo-pero-asegura-que-sin-el-tesla-mo ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Can someone assist me with running queries on the MongoDB collection using Node.js?

In my mongodb collection called "jobs," I have a document format that needs to display all documents matching my query. { "_id": { "$oid": "60a79952e8728be1609f3651" }, "title": "Full Stack Java Develo ...

React TypeScript error: Cannot access property "x" on object of type 'A | B'

Just starting out with react typescript and I've encountered the following typescript error when creating components: interface APIResponseA { a:string[]; b:number; c: string | null; // <- } interface APIResponseB { a:string[] | null; b:number; d: ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

Struggling with establishing connection logic between two database tables using Prisma and JavaScript

I'm facing a perplexing logic problem that is eluding my understanding. Within the context of using next-connect, I have a function designed to update an entry in the database: .put(async (req, res) => { const data = req.body; const { dob ...