How to Make a Post File Upload Request in Angularjs

This post will cover everything that y'all demand to know in practice in order to handle all sorts of file upload scenarios in an Athwart application.

Nosotros are going to acquire 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 call.

This custom component is going to have an upload loading indicator, and it'due south going to support 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 post, we will encompass the post-obit topics:

  • How to upload files in a browser
  • Building 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 Customer
  • How to brandish a file upload progress indicator
  • How to abolish an ongoing file upload
  • Handling the uploaded file on a Node backend
  • How to upload multiple files
  • Summary

Then without farther ado, let's become started learning how to build an Athwart file upload component!

How to Upload Files in a Browser

In lodge to build an Angular file upload component, we need to first understand how to upload files in apparently HTML and Javascript only, and take it from there.

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

This input will permit the user to open a browser file selection dialog and select one or more files (by default, just one file). Here is what this input looks similar:

A plain HTML file upload input

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

Why don't we see file inputs very often?

The problem with this plain file input is that by default it's very hard to style. Some styles applied to it can't exist inverse, and we can't even change the text on the push!

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

Because this file input is impossible to style properly, the near mutual option is to actually never testify information technology to the finish-user, every bit we volition encounter.

How does the input of blazon file work?

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

Here is the output that we run across on the console subsequently the user selects a file:

When the change result 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 we know how all the standard file upload browser functionality works, permit's see how can we build a overnice Angular component to encapsulate it.

Edifice the User Interface of a File Upload Component

Considering a plain input of blazon file is impossible to style properly, what we end up doing is hiding it from the user, and and so building an alternative file upload UI that uses the file input behind the scenes.

Hither is what the template of an initial file upload component could expect like:

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

This patently input text is hidden from the user, as we can meet in the component CSS:

Below the hidden file input, we accept the file-upload container div, which contains the actual UI that the user will run into on the screen.

As an example, we take built this UI with Athwart Material components, but of course, the alternative file upload UI could take whatever form that you like.

This UI could be 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

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 will then cull a file from the file upload dialog, and the change result volition be triggered and handled past onFileSelected().

Uploading a file to the backend using the Angular HTTP Client

Let'south now take a look at our component class and the implementation of
onFileSelected():

Here is what is going in this component:

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

At this betoken, we would already have a working file upload component. But nosotros want to have this component i step further. We desire to be able to display a progress indicator to the user, and besides support upload cancelation.

How to Display a File Upload Progress Indicator

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

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

  • An Athwart Material progress bar, which is visible only while the file upload is still in progress.
  • A cancel upload button, besides only visible when an upload is even so ongoing

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

The manner that we implement the progress indicator, is by 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 come across it in activeness, let'due south have a expect at the final version of the file upload component grade, with all its features implemented:

Every bit we can see, nosotros have set the reportProgress holding to true in our HTTP telephone call, and we have as well fix the discover property to the value events.

This ways that, as the POST telephone call continues, nosotros 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, nosotros are saving the ongoing upload percent in a member variable uploadProgress, which nosotros then use to update the value of the progress indicator bar.

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

Nosotros can make certain that we practice then 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 keep a reference to the RxJs Subscription object that we get when the http$ Appreciable gets subscribed to.

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

While the upload is withal in progress, the user might decide to abolish it by clicking on the abolish button. And so the cancelUpload() upload method is going to go triggered and the HTTP request can exist 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 last version of our file upload component, we can require the user to upload a file of a certain blazon, by using the requiredFileType property:

This property is 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 option dialog volition let the user to select only one file for upload.

Simply using the multiple holding, nosotros can allow the user to select multiple files instead:

Notice that this would need a completely different UI than the one that we accept 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 congenital: a floating dialog with the upload progress of all files, etc.

Handling the uploaded file on a Node backend

The way that you handle the uploaded file in your backend depends on the engineering science that you apply, but let's give a quick example of how to do it if using Node and the Limited framework.

We need to first install the express-fileupload package. We tin and so add this package as a middleware in our Express awarding:

From here, all we have to do is define an Limited 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 contain internally an HTML input of type file, that allows the user to select i or more files from the file organisation.

This file input should exist hidden from the user as it'due south not styleable and replaced past a more user-friendly UI.

Using the file input in the groundwork, we can get a reference to the file via the change event, which nosotros can so utilize to build an HTTP request and send the file to the backend.

I hope that you have enjoyed this post, if you would like to learn a lot more almost Athwart, we recommend checking the Angular Core Deep Dive form, where we will comprehend all of the avant-garde Angular features in detail.

Also, if you have some questions or comments delight let me know in the comments below and I will get back to you lot.

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

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

gonzalezsteris.blogspot.com

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

0 Response to "How to Make a Post File Upload Request in Angularjs"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel