Processing Files for Upload Locally
Environment
Product | Progress® Kendo UI Upload |
Description
How can I locally process files in the Kendo UI for Angular Upload?
Solution
The Upload enables you to process the files entirely on the client side by implementing an HttpInterceptor
and intercepting the upload requests to simulate the success
response.
As of version 5.2.0, the Kendo UI Upload for Angular features a built-in FileSelect component, which is the ready-to-use solution for the current scenario.
The following sample project uses the Upload component to process the selected files locally and display them as an image gallery.
Configuring the Custom Interceptor
Create a custom service that implements the Angular HttpInterceptor
interface and its intercept
method to handle the requests and return success
.
@Injectable()
export class UploadInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url === 'saveUrl') {
const success = of(new HttpResponse({ status: 200 }));
return success;
}
if (req.url === 'removeUrl') {
return of(new HttpResponse({ status: 200 }));
}
return next.handle(req);
}
}
Configuring the Upload
-
Configure the Upload component to handle the
select
event. Optionally, provide an array of file-like objects as the initial state of "selected" files. For more information on rendering initial files, refer to this article.html<kendo-upload [saveUrl]="uploadSaveUrl" [removeUrl]="uploadRemoveUrl" (select)="onSelect($event)" (remove)="onRemove($event)" [restrictions]="myRestrictions" [ngModel]="myFiles" > <kendo-upload-messages select="Add images"> </kendo-upload-messages> </kendo-upload>
-
Process the selected files in the
select
event handler by using the FileReader API. To optionally allow their removal, utilize theremove
event handler.tsuploadSaveUrl = 'saveUrl'; // Has to represent an actual API endpoint. uploadRemoveUrl = 'removeUrl'; // Has to represent an actual API endpoint. myRestrictions = [{ allowedExtensions: ['jpg', 'png'] }]; public myFiles: any[] = [{ name: 'three.jpg', src: 'https://demos.telerik.com/kendo-ui/content/web/foods/3.jpg', size: 1000, uid: 1 }, { name: 'two.jpg', src: 'https://demos.telerik.com/kendo-ui/content/web/foods/2.jpg', size: 2000, uid: 2 }]; public onSelect(ev: SelectEvent): void { ev.files.forEach((file: FileInfo) => { if (file.rawFile) { const reader = new FileReader(); reader.onloadend = () => { this.myFiles.push({...file, src: <string>reader.result}); }; reader.readAsDataURL(file.rawFile); } }); } public onRemove(ev: RemoveEvent): void { ev.files.forEach((file: FileInfo) => { this.myFiles = this.myFiles.filter(f => f.uid !== file.uid); }); }
-
Display the selected images on the page by using an
ngFor
directive.html<img *ngFor="let image of myFiles" height="100" [src]="image.src" style="margin: 5px; border: 1px solid gray;" />
The following example demonstrates the full implementation of the suggested approach.