npm install ng2-file-upload --save
FileUploader
module in your component where you want to use file upload functionality:import { FileUploader } from 'ng2-file-upload';
const uploader = new FileUploader({
url: 'https://example.com/upload',
authToken: 'Bearer ' + localStorage.getItem('token'),
isHTML5: true,
allowedFileType: ['image'],
maxFileSize: 10 * 1024 * 1024 // 10 MB
});
authToken
is the authentication token to send with the request (if required), isHTML5
tells the uploader to use the HTML5 file API, allowedFileType
specifies the allowed file types (here, only images are allowed), andmaxFileSize
sets the maximum file size (here, 10 MB).<input type="file" ng2FileSelect [uploader]="uploader" />
ng2FileSelect
is a directive provided by the Angular File Uploader library.<button type="button" (click)="uploader.uploadAll()">Upload</button>
uploader.uploadAll()
triggers the file upload.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log('File uploaded:', item.file.name, status, response);
};
onCompleteItem
is a callback function that is called when the file upload is completed. You can handle the response here as per your requirement.