Nowadays, we have a lot of platforms where we can easily upload multiple images and videos. The Angular image uploader is standard to upload multiple images, videos, and files on servers. The AngularJS file upload system may seem difficult, but is easy to use.
Using an AngularJS upload file system is not rocket science if we know how to use it step-by-step. It is a web framework that we can use to upload high-quality files. The best part is that users can find an Angular image uploader in different modules.
We have access to unique features, such as a time progress bar, universal Angular compatibility, multiple themes, file name, and localization on our web apps through Angular image uploader.
Before we start using an Angular image uploader, we should know why choosing an Angular image uploader can be our best decision. We get the opportunity to work on a platform that Google manages, maintains, and designs. We, as developers, can use received data to build UI. There is much more to it. So, let’s move to the Angular file upload tutorial.
Browse File Upload
Before building an Angular image uploader component, we need basic knowledge. For example, how can we upload files in HTML or JavaScript? To upload the files in HTML text in a browser, we can use the following key ingredient:
<input type=”file” class=”file-upload” onchange=”console.log(event.target.files)”>
With the help of the above code, the user will get a dialogue box to upload images, videos, or other files. This dialogue box allows us to select a file from our file system. We can send this input to the backend side using a little more JavaScript.
The plain input file may seem very simple, but we find it difficult to design or style in an Angular image uploader. For example, we can face problems like not being able to change the text on our Angular image uploader. It can also make us unable to change the techniques applied to it earlier. It indicates that a lack of customization can be a real challenge once it is styled.
Due to this problem, we don’t primarily use this simple input. When we use the Angular image uploader to upload a particular file, it emits the event “change.” There is a list of files in this event that we selected on the property “target.files”. When our user selects a file, we will get the following output on the console:
{
lastModified: 1601984029839
lastModifiedDate: Tue Oct 06 2020 13:33:49 GMT+0200 (Central European Summer Time)
name: "angular-forms-course-small.jpg"
size: 56411
type: "image/jpeg"
webkitRelativePath: ""
}
The file will not upload on the backend when ‘change’ is triggered. So, we will use an HTTP request to trigger the event ‘change’.
User Interface Creation
Since we know it is hard to style a plain HTML file Angular image uploader, we need to design an alternative file upload UI. But we will also need to hide it from our users. It will use the input file in a hidden way behind the scenes. For example, we can use the following template:
<input type="file" class="file-input"
(change)="onFileSelected($event)" #fileUpload>
<div class="file-upload">
{{fileName || "No file uploaded yet."}}
<button mat-mini-fab color="primary" class="upload-btn"
(click)="fileUpload.click()">
<mat-icon>attach_file</mat-icon>
</button>
</div>
With the help of this Angular image uploader template, we can split the user interface into two parts. We can have a plain file input that opens the file upload box. It will also handle the event ‘change’.
On the other hand, we can see plain input text in component CSS as:
.file-input {
display: none;
}
…
The above one will be hidden from the user.
There, we will get div, a “file-upload” container. It will contain the UI that a user will see.
We can also build this UI with the help of Angular material components. The best part is that the alternative file upload UI can be styled in any design we like. The designed UI can be a drag-and-drop zone or a dialogue.
We can notice that the invisible file and the upload button are linked in the component template. A click handler can easily trigger the file input when our user clicks the blue button. It will take place via fileUpload.click(). This will make the user select a file from the file system, and then onFile.selected will handle the ‘change’ event.
Backend Angular HTTP Client File Upload
So now we must know how to implement onFile.selected(). The component class is given as under:
@Component({
selector: 'file-upload',
templateUrl: "file-upload.component.html",
styleUrls: ["file-upload.component.scss"]
})
export class FileUploadComponent {
fileName = '';
constructor(private http: HttpClient) {}
onFileSelected(event) {
const file:File = event.target.files[0];
if (file) {
this.fileName = file.name;
const formData = new FormData();
formData.append("thumbnail", file);
const upload$ = this.http.post("/api/thumbnail-upload", formData);
upload$.subscribe();
}
}
}
Important Points About This Component:
It accesses the even.target.files property to give us a reference for user-selected files.
We use a standard browser API, FormData, to build a form payload.
Then, we need to send the file to the backend using Angular HTTP for creating an HTTP request.
We will have a working file upload component, so we will need to take more actions on the active file upload component. This is about showing a progress indicator to our users. It will also include an option to support upload cancellation.
Displaying Progress Indicators While Uploading A File
We need to add some extra components to our UI to display the upload progress indicator. The file upload component template looks like this:
<input type="file" class="file-input"
[accept]="requiredFileType"
(change)="onFileSelected($event)" #fileUpload>
<div class="file-upload">
{{fileName || "No file uploaded yet."}}
<button mat-mini-fab color="primary" class="upload-btn"
(click)="fileUpload.click()">
<mat-icon>attach_file</mat-icon>
</button>
</div>
<div class="progress">
<mat-progress-bar class="progress-bar" mode="determinate"
[value]="uploadProgress" *ngIf="uploadProgress">
</mat-progress-bar>
<mat-icon class="cancel-upload" (click)="cancelUpload()"
*ngIf="uploadProgress">delete_forever</mat-icon>
</div>
The final UI has two main elements added to it:
- Cancel Upload button
- Angular Material Progress bar
Both elements show only when the process of upload is in progress.
File Upload Cancellation
We need to reference the RxJs Subscription object to support file upload cancellation. It is possible only when we get subscribed to HTTP Observable.
We can also add the subscription object in our member variable ‘uploadSub’. It will ensure the file upload cancellation when the user’s file is still in progress. We can also trigger the cancelUpload() upload method as an HTTP request will cancel when we unsubscribe from the uploadSub subscription.
The unsubscription will result in the file upload cancellation.
Accepting Specified File Types
When we design the file upload component, we need to ensure that the user can upload a specific file type or provide help in uploading large files. It is possible only by using the requiredFileType property:
<file-upload requiredFileType="image/png"></file-upload>
This property will pass to another property ‘accept’ in the file upload template. It forces the secure uploading of a specific file type in the box.
Uploading Multiple Files Through Angular Image Uploader
We need to use the ‘multiple’ property to enable our users to upload more than one file. For example:
<input type="file" class="file-upload" multiple>
However, we must design a completely different UI to enable this option. A well-styled UI with a progress indicator button can only support a single file upload. To help with multiple uploads, we can choose from different UIs available. For example, we can use a floating dialogue, the progress indicator of various uploaded files.
Node Backend File Upload
Whichever technology we use to handle the uploading of files affects the whole process. For example, if we use the Express and Node frameworks, we can do it as follows:
We have to install the ‘express-fileupload’ package. This package needs to be added to the Express application as a middleware. We can see it as given below:
const fileUpload = require('express-fileupload');
const app: Application = express();
app.use(fileUpload());
Then we need to define an Express route that helps handle the requests for file uploads:
app.route('/api/thumbnail-upload').post(onFileupload);
export function onFileupload(req:Request, res: Response) {
let file = req['files'].thumbnail;
console.log("File uploaded: ", file.name);
...
}
Ready to start building powerful uploading functionality?
We can build multiple custom components to handle the file uploading process in Angular by adding the HTML input file in the file upload component.
This is to enable the user to upload single or multiple files in the system. However, the multiple file uploading process doesn’t support a well-designed UI with a progress indicator bar.
There are different designs of UI available to support multiple file uploading. You should also know that the alternative UI should not display on the screen to the user. We cannot replace it with a more user-friendly design. This is how you can use the file uploading process in Angular image uploader.
Integrate Filestack’s upload API today!
Ayesha Zahra is a Geo Informatics Engineer with hands-on experience in web development (both frontend & backend). Also, she is a technical writer, a passionate programmer, and a video editor. She is always looking for opportunities to excel in her skills & build a strong career.
Read More →