How to Allow User to Only Upload Text File Into Form

This post will cover everything that you need to know in practice in order to handle all sorts of file upload scenarios in an Angular application.

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

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

Table Of Contents

In this mail, we volition cover the following topics:

  • How to upload files in a browser
  • Edifice the user interface of a file upload component
  • Selecting a file from the file system 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
  • Treatment the uploaded file on a Node backend
  • How to upload multiple files
  • Summary

So without further ado, let's become started learning how to build an Angular file upload component!

How to Upload Files in a Browser

In society to build an Angular file upload component, we need to first sympathise how to upload files in plain HTML and Javascript only, and have it from there.

The fundamental ingredient for uploading files in a browser is a plainly HTML input of type file:

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

A plain HTML file upload input

With this file input box, yous can select a file from your file organisation, and then with a bit of Javascript, you lot can already send information technology to a backend.

Why don't we 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 be changed, and nosotros tin can't even change the text on the button!

This is default browser behavior that tin't be changed, and that is why we usually 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 most common selection is to actually never show it to the stop-user, as we will come across.

How does the input of type file work?

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

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

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

At present that we know how all the standard file upload browser functionality works, permit's come across how can nosotros 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 impossible to style properly, what we terminate up doing is hiding information technology from the user, and and so building an alternative file upload UI that uses the file input backside the scenes.

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

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

This obviously input text is subconscious from the user, as we can run into in the component CSS:

Below the hidden file input, we take the file-upload container div, which contains the actual UI that the user volition see on the screen.

As an example, nosotros have congenital this UI with Angular Material components, but of grade, the alternative file upload UI could take whatsoever course that you like.

This UI could be a dialog, a elevate and drib zone, or like in the case of our component, only a styled button:

Example of an Angular Material file upload component

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

The user volition then choose a file from the file upload dialog, and the alter event will exist triggered and handled past onFileSelected().

Uploading a file to the backend using the Athwart HTTP Client

Allow's at present have a expect at our component form and the implementation of
onFileSelected():

Hither is what is going in this component:

  • we are getting a reference to the files that the user selected by accessing the result.target.files property.
  • we then build a form payload by using the FormData API. This is a standard browser API, information technology's not Angular-specific.
  • we and so utilize the Angular HTTP customer to create an HTTP request and transport the file to the backend

At this indicate, we would already have a working file upload component. Only we want to accept this component one pace further. Nosotros want to be able to display a progress indicator to the user, and as well back up 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 Athwart Material progress bar, which is visible only while the file upload is however in progress.
  • A cancel upload push, as well only visible when an upload is notwithstanding ongoing

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

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

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

To see it in activity, let'south take a wait at the terminal version of the file upload component class, with all its features implemented:

Every bit we can see, we have prepare the reportProgress property to true in our HTTP phone call, and nosotros have also set the discover property to the value events.

This means that, as the POST phone call continues, we are going to receive outcome objects reporting the progress of the HTTP request.

These events will be emitted every bit values of the http$ Observable, and come up in unlike types:

  • events of type UploadProgress study the percent of the file that has already been uploaded
  • events of types Response written 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 we and so utilize to update the value of the progress indicator bar.

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

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

How to Cancel an Ongoing File Upload

In order to support file upload cancellation, all we have to is go on a reference to the RxJs Subscription object that we go when the http$ Observable gets subscribed to.

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

While the upload is still 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 volition trigger the firsthand cancelation of the ongoing file upload.

How to accept only files of a certain type

In the terminal version of our file upload component, we can crave the user to upload a file of a certain type, by using the requiredFileType property:

This property is and then passed directly to the accept 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 will allow the user to select simply one file for upload.

But using the multiple property, we can allow the user to select multiple files instead:

Observe that this would need a completely different UI than the 1 that we have built. A styled upload button with a progress indicator only works well for the upload of a single file.

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

Treatment the uploaded file on a Node backend

The mode that y'all handle the uploaded file in your backend depends on the technology that you utilize, but let'south give a quick example of how to do information technology if using Node and the Express framework.

Nosotros need to kickoff install the limited-fileupload package. We can then add this package as a middleware in our Express application:

From hither, all we accept to do is define an Express route to handle the file upload requests:

Summary

The best way to handle file upload in Athwart is to build 1 or more custom components, depending on the supported upload scenarios.

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

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

Using the file input in the background, we tin can get a reference to the file via the change event, which we can then use to build an HTTP request and transport the file to the backend.

I hope that you accept enjoyed this postal service, if y'all would like to larn a lot more about Athwart, we recommend checking the Angular Core Deep Swoop grade, where we volition embrace all of the advanced Angular features in detail.

Also, if y'all have some questions or comments please let me know in the comments below and I will get back to yous.

To become notified of upcoming posts on Athwart, I invite yous to subscribe to our newsletter:

And if you are just getting started learning Angular, take a look at the Athwart for Beginners Course:

lamblealred1975.blogspot.com

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

0 Response to "How to Allow User to Only Upload Text File Into Form"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel