Angular Directives for Handle Image upload
For handling image/file upload handling in Angular we can use below code. We can also change the file size and file type also.
Firstly Create a directive NgImageUploadDirective
import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
@Directive({
selector: '[ngImageUpload]'
})
export class NgImageUploadDirective {
@Input() maxSize: number = 5242880; // 5MB in bytes
@Output() imageUploaded = new EventEmitter<File>();
constructor() { }
@HostListener('change', ['$event.target.files']) handleImageUpload(files: FileList) {
const file = files.item(0);
if (!file) return;
// Check file type
const allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
if (!allowedTypes.includes(file.type)) {
alert('Invalid file type. Only PNG, JPEG and GIF images are allowed.');
return;
}
// Check file size
if (file.size > this.maxSize) {
alert('File size exceeds limit. Maximum allowed size is 5MB.');
return;
}
// Emit event with file object
this.imageUploaded.emit(file);
}
}
This directive listens for the change
event on an input element with the ngImageUpload
selector, which triggers when a user selects an image to upload. The handleImageUpload()
function then performs some validation checks on the selected file, such as checking its file type and size. If the file passes these checks, it emits an event with the selected file object, which can then be used by the parent component.
To use this directive in your component’s HTML template, you would simply add the ngImageUpload
attribute to an <input>
element that allows file uploads:
<input type="file" ngImageUpload (imageUploaded)="handleImageUpload($event)">
In this example, the imageUploaded
event is bound to the handleImageUpload()
function in the component, which receives the uploaded file object as its argument. You can then perform additional actions with the uploaded file as needed.
@Directive({ selector: '[ngImageUpload]' })
: This decorator defines the directive and specifies its selector, which in this case is[ngImageUpload]
. This means that the directive will be applied to any element that has thengImageUpload
attribute.@Input() maxSize: number = 5242880;
: This decorator defines an input property calledmaxSize
, which specifies the maximum allowed file size for image uploads. By default, the maximum size is set to 5MB in bytes.@Output() imageUploaded = new EventEmitter<File>();
: This decorator defines an output property calledimageUploaded
, which is an event emitter that will be used to emit the uploaded image file to the parent component.@HostListener('change', ['$event.target.files'])
: This decorator listens for thechange
event on the host element (i.e. the element to which the directive is applied) and passes thetarget.files
property of the event as an argument to thehandleImageUpload()
function.handleImageUpload(files: FileList) { ... }
: This function takes aFileList
object as its argument, which represents the list of files that were selected for upload. In this case, we only handle the first file in the list, so we use theitem()
method to get the first file object.const allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
: This array specifies the allowed file types for image uploads. In this case, we only allow PNG, JPEG, and GIF images.if (!allowedTypes.includes(file.type)) { ... }
: This condition checks if the selected file'stype
property is one of the allowed types. If the file is not an image or is not one of the allowed types, an error message is displayed to the user.if (file.size > this.maxSize) { ... }
: This condition checks if the selected file'ssize
property exceeds the maximum allowed size.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Interested in scaling your software startup? Check out Circuit.