File Upload Multiple Dont Allow Upload Same Element Again

This post volition cover everything that you need to know in practise in society to handle all sorts of file upload scenarios in an Angular application.

We are going to acquire how to build a fully functional Athwart file upload component, that requires a file of a given extension to be uploaded and sends the file to a backend via an HTTP Mail call.

This custom component is going to have an upload loading indicator, and it's going to support upload cancelation as well. We are going to give as well an example (in Node) of how to handle the file in the backend.

Table Of Contents

In this mail service, we volition cover the following topics:

  • How to upload files in a browser
  • Building the user interface of a file upload component
  • Selecting a file from the file arrangement using a file upload dialog
  • Uploading a file to the backend using the Angular HTTP Client
  • How to brandish a file upload progress indicator
  • How to cancel an ongoing file upload
  • Handling the uploaded file on a Node backend
  • How to upload multiple files
  • Summary

So without further ado, let'due south get started learning how to build an Angular file upload component!

How to Upload Files in a Browser

In order to build an Athwart file upload component, nosotros need to first understand how to upload files in obviously HTML and Javascript only, and take it from in that location.

The key ingredient for uploading files in a browser is a plain HTML input of type file:

This input volition allow the user to open a browser file choice dialog and select one or more files (by default, only 1 file). Here is what this input looks like:

A plain HTML file upload input

With this file input box, y'all can select a file from your file system, and then with a bit of Javascript, you can already send it to a backend.

Why don't nosotros see file inputs very oftentimes?

The trouble with this plain file input is that by default information technology's very hard to style. Some styles applied to it can't exist changed, and we can't fifty-fifty change the text on the button!

This is default browser behavior that can't be changed, and that is why we normally don't see this plain file input on all the interfaces that we use daily, like Gmail, etc.

Because this file input is impossible to style properly, the well-nigh mutual option is to actually never evidence it to the end-user, as we will see.

How does the input of type file piece of work?

When the user chooses a file using the file upload dialog, an event of type
change will be emitted. This result will and then contain the list of files that the user selected on the target.files belongings.

Here is the output that we see on the console after the user selects a file:

When the alter consequence gets triggered, the file is not automatically uploaded to the backend by the browser. Instead, we will demand to trigger an HTTP request ourselves, in response to the change effect.

Now that nosotros know how all the standard file upload browser functionality works, let'due south see how can we build a nice Angular component to encapsulate it.

Building the User Interface of a File Upload Component

Because a plain input of type file is incommunicable to style properly, what we end upwards doing is hiding it from the user, and and so building an alternative file upload UI that uses the file input behind the scenes.

Here is what the template of an initial file upload component could look like:

This user interface is split up upwards into two split up parts. On top, we have a evidently file input, that is used to open the file upload dialog and handle the change consequence.

This apparently input text is subconscious from the user, as we can see in the component CSS:

Below the subconscious file input, we have the file-upload container div, which contains the actual UI that the user will see on the screen.

As an example, nosotros have built this UI with Athwart Material components, only of course, the alternative file upload UI could take whatsoever form that you like.

This UI could exist a dialog, a drag and drop zone, or like in the case of our component, simply a styled push:

Example of an Angular Material file upload component

Find in the component template how the upload blueish button and the invisible file input are linked. When the user clicks on the blue button, a click handler triggers the file input via fileUpload.click().

The user will then cull a file from the file upload dialog, and the alter result will be triggered and handled by onFileSelected().

Uploading a file to the backend using the Angular HTTP Client

Permit's now have a expect at our component class and the implementation of
onFileSelected():

Here is what is going in this component:

  • we are getting a reference to the files that the user selected past accessing the outcome.target.files holding.
  • nosotros then build a course payload past using the FormData API. This is a standard browser API, it's not Angular-specific.
  • nosotros and so apply the Angular HTTP client to create an HTTP request and send the file to the backend

At this point, nosotros would already have a working file upload component. But nosotros desire to have this component one pace further. Nosotros want to be able to display a progress indicator to the user, and too support upload cancelation.

How to Brandish a File Upload Progress Indicator

We are going to add a few more elements to the UI of our file upload component. Here is the final version of the file upload component template:

The two main elements that we have added to the UI are:

  • An Angular Material progress bar, which is visible only while the file upload is nevertheless in progress.
  • A cancel upload push button, also merely visible when an upload is nonetheless ongoing

How to know how much of the file has been uploaded?

The way that we implement the progress indicator, is by using the reportProgress feature of the Angular HTTP client.

With this feature, we tin get notified of the progress of a file upload via multiple events emitted by the HTTP Observable.

To see information technology in action, allow's have a expect at the final version of the file upload component class, with all its features implemented:

As we can see, we take set the reportProgress property to true in our HTTP call, and we have likewise set the observe property to the value events.

This ways that, equally the Postal service phone call continues, we are going to receive event objects reporting the progress of the HTTP request.

These events will be emitted as values of the http$ Observable, and come in different types:

  • events of type UploadProgress written report the percentage of the file that has already been uploaded
  • events of types Response report that the upload has been completed

Using the events of type UploadProgress, we are saving the ongoing upload percentage in a member variable uploadProgress, which nosotros then apply to update the value of the progress indicator bar.

When the upload either completes or fails, nosotros need to hibernate the progress bar from the user.

We can make sure that we do so by using the RxJs finalize operator, which is going to call the reset() method in both cases: upload success or failure.

How to Abolish an Ongoing File Upload

In order to support file upload cancellation, all nosotros accept to is keep a reference to the RxJs Subscription object that we get when the http$ Observable gets subscribed to.

In our component, nosotros store this subscription object in the uploadSub member variable.

While the upload is notwithstanding in progress, the user might decide to cancel it by clicking on the cancel push. Then the cancelUpload() upload method is going to go triggered and the HTTP request can be canceled by unsubscribing from the uploadSub subscription.

This unsubscription will trigger the immediate cancelation of the ongoing file upload.

How to accept only files of a certain type

In the final version of our file upload component, we tin require the user to upload a file of a sure type, by using the requiredFileType property:

This property is then passed directly to the have property of the file input in the file upload template, forcing the user to select a png file from the file upload dialog.

How to Upload Multiple Files

By default, the browser file selection dialog volition permit the user to select simply one file for upload.

Merely using the multiple belongings, we can let the user to select multiple files instead:

Notice that this would need a completely dissimilar UI than the one that we have built. A styled upload button with a progress indicator just works well for the upload of a single file.

For a multi-file upload scenario, there are a diversity of UIs that could be built: a floating dialog with the upload progress of all files, etc.

Handling the uploaded file on a Node backend

The way that you lot handle the uploaded file in your backend depends on the technology that you apply, but let'south requite a quick example of how to practice it if using Node and the Express framework.

Nosotros need to first install the express-fileupload package. Nosotros can then add together this package as a middleware in our Limited application:

From here, all we have to do is define an Express road to handle the file upload requests:

Summary

The best style to handle file upload in Angular is to build one or more custom components, depending on the supported upload scenarios.

A file upload component needs to comprise internally an HTML input of type file, that allows the user to select one or more files from the file system.

This file input should be subconscious from the user as it's not styleable and replaced by a more than user-friendly UI.

Using the file input in the groundwork, we can become a reference to the file via the change outcome, which nosotros tin can and so use to build an HTTP request and transport the file to the backend.

I hope that you accept enjoyed this mail, if y'all would like to larn a lot more most Athwart, we recommend checking the Angular Core Deep Dive grade, where we volition cover all of the advanced Angular features in item.

Also, if you have some questions or comments please let me know in the comments below and I will become dorsum to you.

To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:

And if you are simply getting started learning Angular, have a look at the Athwart for Beginners Grade:

mitchellwhady1951.blogspot.com

Source: https://blog.angular-university.io/angular-file-upload/

0 Response to "File Upload Multiple Dont Allow Upload Same Element Again"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel