kandi background
Explore Kits

DownloadService | Service Muti-Thread Download(Service多线程下载) | Download Utils library

 by   BillKalin Java Version: Current License: No License

 by   BillKalin Java Version: Current License: No License

Download this library from

kandi X-RAY | DownloadService Summary

DownloadService is a Java library typically used in Utilities, Download Utils applications. DownloadService has no bugs, it has no vulnerabilities and it has low support. However DownloadService build file is not available. You can download it from GitHub.
Service Muti-Thread Download(Service多线程下载) 基于Service 多线程下载。.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • DownloadService has a low active ecosystem.
  • It has 13 star(s) with 4 fork(s). There are no watchers for this library.
  • It had no major release in the last 12 months.
  • DownloadService has no issues reported. There are no pull requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of DownloadService is current.
DownloadService Support
Best in #Download Utils
Average in #Download Utils
DownloadService Support
Best in #Download Utils
Average in #Download Utils

quality kandi Quality

  • DownloadService has 0 bugs and 0 code smells.
DownloadService Quality
Best in #Download Utils
Average in #Download Utils
DownloadService Quality
Best in #Download Utils
Average in #Download Utils

securitySecurity

  • DownloadService has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • DownloadService code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
DownloadService Security
Best in #Download Utils
Average in #Download Utils
DownloadService Security
Best in #Download Utils
Average in #Download Utils

license License

  • DownloadService does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.
DownloadService License
Best in #Download Utils
Average in #Download Utils
DownloadService License
Best in #Download Utils
Average in #Download Utils

buildReuse

  • DownloadService releases are not available. You will need to build from source code and install.
  • DownloadService has no build file. You will be need to create the build yourself to build the component from source.
DownloadService Reuse
Best in #Download Utils
Average in #Download Utils
DownloadService Reuse
Best in #Download Utils
Average in #Download Utils
Top functions reviewed by kandi - BETA

kandi has reviewed DownloadService and discovered the below as its top functions. This is intended to give you an instant insight into DownloadService implemented functionality, and help decide if they suit your requirements.

  • OnCreateOptions menu .
    • Sets the activity to be saved .
      • Sends the view back to the given view .

        Get all kandi verified functions for this library.

        Get all kandi verified functions for this library.

        DownloadService Key Features

        Service Muti-Thread Download(Service多线程下载)

        Angular 13 download file from api in entire app (.Net 6)

        copy iconCopydownload iconDownload
        private getFilenameFromContentDisposition(contentDisposition: string): string {
            const regex = /filename=(?<filename>[^,;]+);/g;
            const match = regex.exec(contentDisposition);
            let filename = null; // or any other value you consider default
            if (typeof match !== 'undefined' && match !== null) {
                filename = match.groups['filename'];
            } 
            return filename; 
        }
        
         services.AddCors(options =>
                    {
        
                        options.AddDefaultPolicy(builder => builder
                         .AllowAnyMethod()
                         .AllowAnyHeader()
                          .WithExposedHeaders("Content-Disposition")    ----This line i have added
                         .SetIsOriginAllowed(origin => true) // allow any origin
                         .AllowCredentials());
                    });
        

        Download Many heavy files in zip. Correct implementation

        copy iconCopydownload iconDownload
        const onezip = require('onezip');
        const path = require('path');
        const cwd = process.cwd();
        const name = 'pipe.tar.gz';
        const from = cwd + '/pipe-io';
        const to = path.join(cwd, name);
        
        const pack = onezip.pack(from, to, [
            'LICENSE',
            'README.md',
            'package.json',
        ]);
        
        pack.on('file', (name) => {
            console.log(name);
        });
        
        pack.on('start', () => {
            console.log('start packing');
        });
        
        pack.on('progress', (percent) => {        // this will help you with what you are seeking
            console.log(percent + '%');
        });
        
        pack.on('error', (error) => {
            console.error(error);
        });
        
        pack.on('end', () => {
            console.log('done');
        });
        
        Uncaught (in promise): RangeError: Array buffer allocation failed
        
        import {
            HttpClient,
            HttpEvent,
            HttpEventType,
            HttpHeaderResponse,
            HttpProgressEvent,
            HttpResponse,
            HttpUserEvent
        } from '@angular/common/http';
        import {Injectable} from '@angular/core';
        import {combineLatest, Observable} from 'rxjs';
        import {scan} from 'rxjs/operators';
        import JSZip from 'jszip';
        
        export class DownloadModel {
            link: string = '';
            fileSize: number = 0;
            fileName: string = '';
        }
        
        export interface DownloadStatus<T> {
            progress: number;
            state: 'PENDING' | 'IN_PROGRESS' | 'DONE' | 'SENT';
            body: T | null;
            httpEvent: HttpEvent<unknown> | null;
            downloadModel: DownloadModel;
        }
        
        export interface ZipStatus<T> {
            progress: number;
            state: 'PENDING' | 'DOWNLOADING' | 'DOWNLOADED' | 'ZIPPING' | 'DONE';
            body: {
                downloadModel: DownloadModel,
                downloaded: Blob | null
            }[];
            zipFile: Blob | null;
            httpEvent: HttpEvent<unknown> | null;
        }
        
        @Injectable({providedIn: 'root'})
        export class DownloadService {
            constructor(private httpClient: HttpClient) {
            }
        
            public downloadMultiple(downloadLinks: DownloadModel[]): Observable<DownloadStatus<Blob>[]> {
                return combineLatest(downloadLinks.map((downloadModel): Observable<DownloadStatus<Blob>> => {
                            return this.httpClient.get(downloadModel.link, {
                                reportProgress: true,
                                observe: 'events',
                                responseType: 'blob'
                            }).pipe(
                                scan((uploadStatus: DownloadStatus<Blob>, httpEvent: HttpEvent<Blob>, index: number): DownloadStatus<Blob> => {
                                    if (this.isHttpResponse(httpEvent)) {
        
                                        return {
                                            progress: 100,
                                            state: 'DONE',
                                            body: httpEvent.body,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpSent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
        
                                        };
                                    }
        
                                    if (this.isHttpUserEvent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpHeaderResponse(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpProgressEvent(httpEvent)) {
        
                                        return {
                                            progress: Math.round((100 * httpEvent.loaded) / downloadModel.fileSize),
                                            state: 'IN_PROGRESS',
                                            httpEvent,
                                            body: null,
                                            downloadModel
                                        };
                                    }
        
        
                                    console.log(httpEvent);
        
                                    throw new Error('unknown HttpEvent');
        
                                }, {state: 'PENDING', progress: 0, body: null, httpEvent: null} as DownloadStatus<Blob>));
                        }
                    )
                );
        
            }
        
            zipMultiple(downloadMultiple: Observable<DownloadStatus<Blob>[]>): Observable<ZipStatus<Blob>> {
        
                return new Observable<ZipStatus<Blob>>(((subscriber) => {
        
                    downloadMultiple.pipe(
                        scan((uploadStatus: ZipStatus<Blob>, httpEvent: DownloadStatus<Blob>[], index: number): ZipStatus<Blob> => {
                            if (httpEvent.some((x) => x.state === 'SENT')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
                            if (httpEvent.some((x) => x.state === 'PENDING')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.some((x) => x.state === 'IN_PROGRESS')) {
                                return {
                                    state: 'DOWNLOADING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.every((x) => x.state === 'DONE')) {
                                return {
                                    state: 'DOWNLOADED',
                                    body: httpEvent.map(x => {
                                        return {
                                            downloadModel: x.downloadModel,
                                            downloaded: x.body
                                        };
                                    }),
                                    httpEvent: null,
                                    progress: 50,
                                    zipFile: null
                                };
                            }
        
                            throw new Error('ZipStatus<Blob> unhandled switch case');
        
                        }, {state: 'PENDING', progress: 0, body: [], httpEvent: null, zipFile: null} as ZipStatus<Blob>)
                    ).subscribe({
                        next: (zipStatus) => {
                            if (zipStatus.state !== 'DOWNLOADED') {
                                subscriber.next(zipStatus);
                            } else {
                                this.zip(zipStatus.body.map(x => {
                                    return {
                                        fileData: x.downloaded as Blob,
                                        fileName: x.downloadModel.fileName
                                    };
                                })).subscribe({
                                    next: (data) => {
                                        // console.log('zipping next');
                                        subscriber.next(data);
                                    },
                                    complete: () => {
                                        // console.log('zipping complete');
                                        subscriber.complete();
                                    },
                                    error: (error) => {
                                        // console.log('zipping error');
        
                                    }
                                });
        
                            }
                        },
                        complete: () => {
                            // console.log('zip$ source complete: ');
        
                        },
                        error: (error) => {
                            // console.log('zip$ source error: ', error);
                        }
                    });
        
        
                }));
        
            }
        
            private zip(files: { fileName: string, fileData: Blob }[]): Observable<ZipStatus<Blob>> {
                return new Observable((subscriber) => {
                    const zip = new JSZip();
        
                    files.forEach(fileModel => {
                        zip.file(fileModel.fileName, fileModel.fileData);
                    });
        
                    zip.generateAsync({type: "blob", streamFiles: true}, (metadata) => {
                        subscriber.next({
                            state: 'ZIPPING',
                            body: [],
                            httpEvent: null,
                            progress: Math.trunc(metadata.percent / 2) + 50,
                            zipFile: null
                        });
        
                    }).then(function (content) {
                        subscriber.next({
                            state: 'DONE',
                            body: [],
                            httpEvent: null,
                            progress: 100,
                            zipFile: content
                        });
        
                        subscriber.complete();
                    });
                });
            }
        
            private isHttpSent<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Sent;
            }
        
            private isHttpResponse<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Response;
            }
        
        
            private isHttpHeaderResponse<T>(event: HttpEvent<T>): event is HttpHeaderResponse {
                return event.type === HttpEventType.ResponseHeader;
            }
        
        
            private isHttpUserEvent<T>(event: HttpEvent<T>): event is HttpUserEvent<T> {
                return event.type === HttpEventType.User;
            }
        
            private isHttpProgressEvent(event: HttpEvent<Blob>): event is HttpProgressEvent {
                return (
                    event.type === HttpEventType.DownloadProgress ||
                    event.type === HttpEventType.UploadProgress
                );
            }
        }
        
        export class AppComponent {
            constructor(
                private http: HttpClient,
                private downloadService: DownloadService
            ) {
            }
        
            start() {
                console.log('start');
                const file1 = new DownloadModel();
                file1.link = 'http://localhost:3000?name=1.jpg';
                file1.fileSize = 41252062;
                file1.fileName = '1.jpg';
                const file2 = new DownloadModel();
                file2.link = 'http://localhost:3000?name=2.jpg';
                file2.fileSize = 39986505;
                file2.fileName = '2.jpg';
        
                const download$ = this.downloadService.downloadMultiple([file1, file2]).pipe(tap({
                    next: (data) => {
                        // console.log('download$ next: ', data);
                    },
                    complete: () => {
                        // console.log('download$ complete: ');
        
                    },
                    error: (error) => {
                        // console.log('download$ error: ', error);
        
                    }
                }));
        
                const zip$ = this.downloadService.zipMultiple(download$);
        
                zip$
                    .pipe(distinctUntilKeyChanged('progress')).subscribe({
                    next: (data) => {
                        console.log('zip$ next: ', data);
        
                        if (data.zipFile) {
                            const downloadAncher = document.createElement("a");
                            downloadAncher.style.display = "none";
                            downloadAncher.href = URL.createObjectURL(data.zipFile);
                            downloadAncher.download = 'images.zip';
                            downloadAncher.click();
                        }
                    },
                    complete: () => {
                        console.log('zip$ complete: ');
        
                    },
                    error: (error) => {
                        console.log('zip$ error: ', error);
        
                    }
                });
            }
        }
        
        Uncaught (in promise): RangeError: Array buffer allocation failed
        
        import {
            HttpClient,
            HttpEvent,
            HttpEventType,
            HttpHeaderResponse,
            HttpProgressEvent,
            HttpResponse,
            HttpUserEvent
        } from '@angular/common/http';
        import {Injectable} from '@angular/core';
        import {combineLatest, Observable} from 'rxjs';
        import {scan} from 'rxjs/operators';
        import JSZip from 'jszip';
        
        export class DownloadModel {
            link: string = '';
            fileSize: number = 0;
            fileName: string = '';
        }
        
        export interface DownloadStatus<T> {
            progress: number;
            state: 'PENDING' | 'IN_PROGRESS' | 'DONE' | 'SENT';
            body: T | null;
            httpEvent: HttpEvent<unknown> | null;
            downloadModel: DownloadModel;
        }
        
        export interface ZipStatus<T> {
            progress: number;
            state: 'PENDING' | 'DOWNLOADING' | 'DOWNLOADED' | 'ZIPPING' | 'DONE';
            body: {
                downloadModel: DownloadModel,
                downloaded: Blob | null
            }[];
            zipFile: Blob | null;
            httpEvent: HttpEvent<unknown> | null;
        }
        
        @Injectable({providedIn: 'root'})
        export class DownloadService {
            constructor(private httpClient: HttpClient) {
            }
        
            public downloadMultiple(downloadLinks: DownloadModel[]): Observable<DownloadStatus<Blob>[]> {
                return combineLatest(downloadLinks.map((downloadModel): Observable<DownloadStatus<Blob>> => {
                            return this.httpClient.get(downloadModel.link, {
                                reportProgress: true,
                                observe: 'events',
                                responseType: 'blob'
                            }).pipe(
                                scan((uploadStatus: DownloadStatus<Blob>, httpEvent: HttpEvent<Blob>, index: number): DownloadStatus<Blob> => {
                                    if (this.isHttpResponse(httpEvent)) {
        
                                        return {
                                            progress: 100,
                                            state: 'DONE',
                                            body: httpEvent.body,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpSent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
        
                                        };
                                    }
        
                                    if (this.isHttpUserEvent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpHeaderResponse(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpProgressEvent(httpEvent)) {
        
                                        return {
                                            progress: Math.round((100 * httpEvent.loaded) / downloadModel.fileSize),
                                            state: 'IN_PROGRESS',
                                            httpEvent,
                                            body: null,
                                            downloadModel
                                        };
                                    }
        
        
                                    console.log(httpEvent);
        
                                    throw new Error('unknown HttpEvent');
        
                                }, {state: 'PENDING', progress: 0, body: null, httpEvent: null} as DownloadStatus<Blob>));
                        }
                    )
                );
        
            }
        
            zipMultiple(downloadMultiple: Observable<DownloadStatus<Blob>[]>): Observable<ZipStatus<Blob>> {
        
                return new Observable<ZipStatus<Blob>>(((subscriber) => {
        
                    downloadMultiple.pipe(
                        scan((uploadStatus: ZipStatus<Blob>, httpEvent: DownloadStatus<Blob>[], index: number): ZipStatus<Blob> => {
                            if (httpEvent.some((x) => x.state === 'SENT')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
                            if (httpEvent.some((x) => x.state === 'PENDING')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.some((x) => x.state === 'IN_PROGRESS')) {
                                return {
                                    state: 'DOWNLOADING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.every((x) => x.state === 'DONE')) {
                                return {
                                    state: 'DOWNLOADED',
                                    body: httpEvent.map(x => {
                                        return {
                                            downloadModel: x.downloadModel,
                                            downloaded: x.body
                                        };
                                    }),
                                    httpEvent: null,
                                    progress: 50,
                                    zipFile: null
                                };
                            }
        
                            throw new Error('ZipStatus<Blob> unhandled switch case');
        
                        }, {state: 'PENDING', progress: 0, body: [], httpEvent: null, zipFile: null} as ZipStatus<Blob>)
                    ).subscribe({
                        next: (zipStatus) => {
                            if (zipStatus.state !== 'DOWNLOADED') {
                                subscriber.next(zipStatus);
                            } else {
                                this.zip(zipStatus.body.map(x => {
                                    return {
                                        fileData: x.downloaded as Blob,
                                        fileName: x.downloadModel.fileName
                                    };
                                })).subscribe({
                                    next: (data) => {
                                        // console.log('zipping next');
                                        subscriber.next(data);
                                    },
                                    complete: () => {
                                        // console.log('zipping complete');
                                        subscriber.complete();
                                    },
                                    error: (error) => {
                                        // console.log('zipping error');
        
                                    }
                                });
        
                            }
                        },
                        complete: () => {
                            // console.log('zip$ source complete: ');
        
                        },
                        error: (error) => {
                            // console.log('zip$ source error: ', error);
                        }
                    });
        
        
                }));
        
            }
        
            private zip(files: { fileName: string, fileData: Blob }[]): Observable<ZipStatus<Blob>> {
                return new Observable((subscriber) => {
                    const zip = new JSZip();
        
                    files.forEach(fileModel => {
                        zip.file(fileModel.fileName, fileModel.fileData);
                    });
        
                    zip.generateAsync({type: "blob", streamFiles: true}, (metadata) => {
                        subscriber.next({
                            state: 'ZIPPING',
                            body: [],
                            httpEvent: null,
                            progress: Math.trunc(metadata.percent / 2) + 50,
                            zipFile: null
                        });
        
                    }).then(function (content) {
                        subscriber.next({
                            state: 'DONE',
                            body: [],
                            httpEvent: null,
                            progress: 100,
                            zipFile: content
                        });
        
                        subscriber.complete();
                    });
                });
            }
        
            private isHttpSent<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Sent;
            }
        
            private isHttpResponse<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Response;
            }
        
        
            private isHttpHeaderResponse<T>(event: HttpEvent<T>): event is HttpHeaderResponse {
                return event.type === HttpEventType.ResponseHeader;
            }
        
        
            private isHttpUserEvent<T>(event: HttpEvent<T>): event is HttpUserEvent<T> {
                return event.type === HttpEventType.User;
            }
        
            private isHttpProgressEvent(event: HttpEvent<Blob>): event is HttpProgressEvent {
                return (
                    event.type === HttpEventType.DownloadProgress ||
                    event.type === HttpEventType.UploadProgress
                );
            }
        }
        
        export class AppComponent {
            constructor(
                private http: HttpClient,
                private downloadService: DownloadService
            ) {
            }
        
            start() {
                console.log('start');
                const file1 = new DownloadModel();
                file1.link = 'http://localhost:3000?name=1.jpg';
                file1.fileSize = 41252062;
                file1.fileName = '1.jpg';
                const file2 = new DownloadModel();
                file2.link = 'http://localhost:3000?name=2.jpg';
                file2.fileSize = 39986505;
                file2.fileName = '2.jpg';
        
                const download$ = this.downloadService.downloadMultiple([file1, file2]).pipe(tap({
                    next: (data) => {
                        // console.log('download$ next: ', data);
                    },
                    complete: () => {
                        // console.log('download$ complete: ');
        
                    },
                    error: (error) => {
                        // console.log('download$ error: ', error);
        
                    }
                }));
        
                const zip$ = this.downloadService.zipMultiple(download$);
        
                zip$
                    .pipe(distinctUntilKeyChanged('progress')).subscribe({
                    next: (data) => {
                        console.log('zip$ next: ', data);
        
                        if (data.zipFile) {
                            const downloadAncher = document.createElement("a");
                            downloadAncher.style.display = "none";
                            downloadAncher.href = URL.createObjectURL(data.zipFile);
                            downloadAncher.download = 'images.zip';
                            downloadAncher.click();
                        }
                    },
                    complete: () => {
                        console.log('zip$ complete: ');
        
                    },
                    error: (error) => {
                        console.log('zip$ error: ', error);
        
                    }
                });
            }
        }
        
        Uncaught (in promise): RangeError: Array buffer allocation failed
        
        import {
            HttpClient,
            HttpEvent,
            HttpEventType,
            HttpHeaderResponse,
            HttpProgressEvent,
            HttpResponse,
            HttpUserEvent
        } from '@angular/common/http';
        import {Injectable} from '@angular/core';
        import {combineLatest, Observable} from 'rxjs';
        import {scan} from 'rxjs/operators';
        import JSZip from 'jszip';
        
        export class DownloadModel {
            link: string = '';
            fileSize: number = 0;
            fileName: string = '';
        }
        
        export interface DownloadStatus<T> {
            progress: number;
            state: 'PENDING' | 'IN_PROGRESS' | 'DONE' | 'SENT';
            body: T | null;
            httpEvent: HttpEvent<unknown> | null;
            downloadModel: DownloadModel;
        }
        
        export interface ZipStatus<T> {
            progress: number;
            state: 'PENDING' | 'DOWNLOADING' | 'DOWNLOADED' | 'ZIPPING' | 'DONE';
            body: {
                downloadModel: DownloadModel,
                downloaded: Blob | null
            }[];
            zipFile: Blob | null;
            httpEvent: HttpEvent<unknown> | null;
        }
        
        @Injectable({providedIn: 'root'})
        export class DownloadService {
            constructor(private httpClient: HttpClient) {
            }
        
            public downloadMultiple(downloadLinks: DownloadModel[]): Observable<DownloadStatus<Blob>[]> {
                return combineLatest(downloadLinks.map((downloadModel): Observable<DownloadStatus<Blob>> => {
                            return this.httpClient.get(downloadModel.link, {
                                reportProgress: true,
                                observe: 'events',
                                responseType: 'blob'
                            }).pipe(
                                scan((uploadStatus: DownloadStatus<Blob>, httpEvent: HttpEvent<Blob>, index: number): DownloadStatus<Blob> => {
                                    if (this.isHttpResponse(httpEvent)) {
        
                                        return {
                                            progress: 100,
                                            state: 'DONE',
                                            body: httpEvent.body,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpSent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
        
                                        };
                                    }
        
                                    if (this.isHttpUserEvent(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpHeaderResponse(httpEvent)) {
        
                                        return {
                                            progress: 0,
                                            state: 'PENDING',
                                            body: null,
                                            httpEvent,
                                            downloadModel
                                        };
                                    }
        
                                    if (this.isHttpProgressEvent(httpEvent)) {
        
                                        return {
                                            progress: Math.round((100 * httpEvent.loaded) / downloadModel.fileSize),
                                            state: 'IN_PROGRESS',
                                            httpEvent,
                                            body: null,
                                            downloadModel
                                        };
                                    }
        
        
                                    console.log(httpEvent);
        
                                    throw new Error('unknown HttpEvent');
        
                                }, {state: 'PENDING', progress: 0, body: null, httpEvent: null} as DownloadStatus<Blob>));
                        }
                    )
                );
        
            }
        
            zipMultiple(downloadMultiple: Observable<DownloadStatus<Blob>[]>): Observable<ZipStatus<Blob>> {
        
                return new Observable<ZipStatus<Blob>>(((subscriber) => {
        
                    downloadMultiple.pipe(
                        scan((uploadStatus: ZipStatus<Blob>, httpEvent: DownloadStatus<Blob>[], index: number): ZipStatus<Blob> => {
                            if (httpEvent.some((x) => x.state === 'SENT')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
                            if (httpEvent.some((x) => x.state === 'PENDING')) {
                                return {
                                    state: 'PENDING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.some((x) => x.state === 'IN_PROGRESS')) {
                                return {
                                    state: 'DOWNLOADING',
                                    body: [],
                                    httpEvent: null,
                                    progress: httpEvent.reduce((prev, curr) => prev + curr.progress, 0) / httpEvent.length / 2,
                                    zipFile: null
                                };
                            }
        
                            if (httpEvent.every((x) => x.state === 'DONE')) {
                                return {
                                    state: 'DOWNLOADED',
                                    body: httpEvent.map(x => {
                                        return {
                                            downloadModel: x.downloadModel,
                                            downloaded: x.body
                                        };
                                    }),
                                    httpEvent: null,
                                    progress: 50,
                                    zipFile: null
                                };
                            }
        
                            throw new Error('ZipStatus<Blob> unhandled switch case');
        
                        }, {state: 'PENDING', progress: 0, body: [], httpEvent: null, zipFile: null} as ZipStatus<Blob>)
                    ).subscribe({
                        next: (zipStatus) => {
                            if (zipStatus.state !== 'DOWNLOADED') {
                                subscriber.next(zipStatus);
                            } else {
                                this.zip(zipStatus.body.map(x => {
                                    return {
                                        fileData: x.downloaded as Blob,
                                        fileName: x.downloadModel.fileName
                                    };
                                })).subscribe({
                                    next: (data) => {
                                        // console.log('zipping next');
                                        subscriber.next(data);
                                    },
                                    complete: () => {
                                        // console.log('zipping complete');
                                        subscriber.complete();
                                    },
                                    error: (error) => {
                                        // console.log('zipping error');
        
                                    }
                                });
        
                            }
                        },
                        complete: () => {
                            // console.log('zip$ source complete: ');
        
                        },
                        error: (error) => {
                            // console.log('zip$ source error: ', error);
                        }
                    });
        
        
                }));
        
            }
        
            private zip(files: { fileName: string, fileData: Blob }[]): Observable<ZipStatus<Blob>> {
                return new Observable((subscriber) => {
                    const zip = new JSZip();
        
                    files.forEach(fileModel => {
                        zip.file(fileModel.fileName, fileModel.fileData);
                    });
        
                    zip.generateAsync({type: "blob", streamFiles: true}, (metadata) => {
                        subscriber.next({
                            state: 'ZIPPING',
                            body: [],
                            httpEvent: null,
                            progress: Math.trunc(metadata.percent / 2) + 50,
                            zipFile: null
                        });
        
                    }).then(function (content) {
                        subscriber.next({
                            state: 'DONE',
                            body: [],
                            httpEvent: null,
                            progress: 100,
                            zipFile: content
                        });
        
                        subscriber.complete();
                    });
                });
            }
        
            private isHttpSent<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Sent;
            }
        
            private isHttpResponse<T>(event: HttpEvent<T>): event is HttpResponse<T> {
                return event.type === HttpEventType.Response;
            }
        
        
            private isHttpHeaderResponse<T>(event: HttpEvent<T>): event is HttpHeaderResponse {
                return event.type === HttpEventType.ResponseHeader;
            }
        
        
            private isHttpUserEvent<T>(event: HttpEvent<T>): event is HttpUserEvent<T> {
                return event.type === HttpEventType.User;
            }
        
            private isHttpProgressEvent(event: HttpEvent<Blob>): event is HttpProgressEvent {
                return (
                    event.type === HttpEventType.DownloadProgress ||
                    event.type === HttpEventType.UploadProgress
                );
            }
        }
        
        export class AppComponent {
            constructor(
                private http: HttpClient,
                private downloadService: DownloadService
            ) {
            }
        
            start() {
                console.log('start');
                const file1 = new DownloadModel();
                file1.link = 'http://localhost:3000?name=1.jpg';
                file1.fileSize = 41252062;
                file1.fileName = '1.jpg';
                const file2 = new DownloadModel();
                file2.link = 'http://localhost:3000?name=2.jpg';
                file2.fileSize = 39986505;
                file2.fileName = '2.jpg';
        
                const download$ = this.downloadService.downloadMultiple([file1, file2]).pipe(tap({
                    next: (data) => {
                        // console.log('download$ next: ', data);
                    },
                    complete: () => {
                        // console.log('download$ complete: ');
        
                    },
                    error: (error) => {
                        // console.log('download$ error: ', error);
        
                    }
                }));
        
                const zip$ = this.downloadService.zipMultiple(download$);
        
                zip$
                    .pipe(distinctUntilKeyChanged('progress')).subscribe({
                    next: (data) => {
                        console.log('zip$ next: ', data);
        
                        if (data.zipFile) {
                            const downloadAncher = document.createElement("a");
                            downloadAncher.style.display = "none";
                            downloadAncher.href = URL.createObjectURL(data.zipFile);
                            downloadAncher.download = 'images.zip';
                            downloadAncher.click();
                        }
                    },
                    complete: () => {
                        console.log('zip$ complete: ');
        
                    },
                    error: (error) => {
                        console.log('zip$ error: ', error);
        
                    }
                });
            }
        }
        

        Not able to create ZIP file through Lambda function

        copy iconCopydownload iconDownload
        public static void CreateFromDirectory (string sourceDirectoryName, string destinationArchiveFileName);
        
        ZipFile.CreateFromDirectory(@"/tmp/files_to_zip/", "/tmp/test.zip");
        
        public static void CreateFromDirectory (string sourceDirectoryName, string destinationArchiveFileName);
        
        ZipFile.CreateFromDirectory(@"/tmp/files_to_zip/", "/tmp/test.zip");
        

        Angular / RxJs: Download Progress

        copy iconCopydownload iconDownload
        return this.http.request(req).pipe(
          map(event => ({
            progress: this.getPercentage(event),
            response: event
          })),
        );
        
        this.downloadService
          .downloadFile(url, RequestType.post, ActionType.download, body)
          .subscribe({
            next: ({progress, response}) => {
              this.progress = progress;
              // use response
            },
            error: (error: any) => {
              // handle errors
            }
          });
        
        return this.http.request(req).pipe(
          map(event => ({
            progress: this.getPercentage(event),
            response: event
          })),
        );
        
        this.downloadService
          .downloadFile(url, RequestType.post, ActionType.download, body)
          .subscribe({
            next: ({progress, response}) => {
              this.progress = progress;
              // use response
            },
            error: (error: any) => {
              // handle errors
            }
          });
        

        Cannot call method in my service inside my component in Angular

        copy iconCopydownload iconDownload
        public downloadpdf(elementRef: ElementRef) {
                const nativeElement = elementRef.nativeElement;
                const html = htmlToPdfmake(nativeElement.innerHTML);
                const documentDefinition = { content: html };
                pdfMake.createPdf(documentDefinition).download();         
         }
        
        downloadAsPDF(){
               this.ds.downloadpdf(this.pdfTable);
        }
                
        
        public downloadpdf(elementRef: ElementRef) {
                const nativeElement = elementRef.nativeElement;
                const html = htmlToPdfmake(nativeElement.innerHTML);
                const documentDefinition = { content: html };
                pdfMake.createPdf(documentDefinition).download();         
         }
        
        downloadAsPDF(){
               this.ds.downloadpdf(this.pdfTable);
        }
                
        

        Scala compile error “value max is not a member of Int&quot;

        copy iconCopydownload iconDownload
        import Predef.intWrapper
        tokensDAO.getTokenSeq().map(...)
        

        How to run Jenkins with Docker on Kubernetes?

        copy iconCopydownload iconDownload
        kubectl describe services my-service
        

        Queue download using Retrofit

        copy iconCopydownload iconDownload
        class DownloadVideoWorker(
            private val context: Context,
            private val params: WorkerParameters,
            private val downloadApi: DownloadApi
        ) : CoroutineWorker(context, params) {
        
            override suspend fun doWork(): Result {
                val videos = inputData.getStringArray(VIDEOS)
                //Download videos
                return success()
            }
        
            companion object {
                const val VIDEOS: String = "VIDEOS"
            
                fun enqueue(videos: Array<String>): LiveData<WorkInfo> {
                    val downloadWorker = OneTimeWorkRequestBuilder<DownloadVideoWorker>()
                        .setInputData(Data.Builder().putStringArray(VIDEOS, videos).build())
                        .build()
                    val workManager = WorkManager.getInstance()
                    workManager.enqueue(downloadWorker)
                    return workManager.getWorkInfoByIdLiveData(downloadWorker.id)
                }
            }
        }
        
        class DownloadViewModel() : ViewModel() {
            private var listOfVideos: Array<String> // Videos urls
        
            fun downloadVideos(): LiveData<WorkInfo> {
                val videosToDownload = retrieveNextThreeVideos()
                return DownloadVideoWorker.enqueue(videos)
            }
            
            fun retrieveNextThreeVideos(): Array<String> {
                if(listOfVideos.size >= 3) {
                    val videosToDownload = listOfVideos.subList(0, 3)
                    videosToDownload.forEach { listOfVideos.remove(it) }
                    return videosToDownload
                }
                return listOfVideos
            }
        }
        
        
            fun downloadVideos() {
                documentsViewModel.downloadVideos().observe(this, Observer {
                    when (it.state) {
                        WorkInfo.State.SUCCEEDED -> {
                            downloadVideos()
                        }
                        WorkInfo.State.FAILED -> {
                            // Handle error result
                        }
                    }
                })
            }
        
        class DownloadVideoWorker(
            private val context: Context,
            private val params: WorkerParameters,
            private val downloadApi: DownloadApi
        ) : CoroutineWorker(context, params) {
        
            override suspend fun doWork(): Result {
                val videos = inputData.getStringArray(VIDEOS)
                //Download videos
                return success()
            }
        
            companion object {
                const val VIDEOS: String = "VIDEOS"
            
                fun enqueue(videos: Array<String>): LiveData<WorkInfo> {
                    val downloadWorker = OneTimeWorkRequestBuilder<DownloadVideoWorker>()
                        .setInputData(Data.Builder().putStringArray(VIDEOS, videos).build())
                        .build()
                    val workManager = WorkManager.getInstance()
                    workManager.enqueue(downloadWorker)
                    return workManager.getWorkInfoByIdLiveData(downloadWorker.id)
                }
            }
        }
        
        class DownloadViewModel() : ViewModel() {
            private var listOfVideos: Array<String> // Videos urls
        
            fun downloadVideos(): LiveData<WorkInfo> {
                val videosToDownload = retrieveNextThreeVideos()
                return DownloadVideoWorker.enqueue(videos)
            }
            
            fun retrieveNextThreeVideos(): Array<String> {
                if(listOfVideos.size >= 3) {
                    val videosToDownload = listOfVideos.subList(0, 3)
                    videosToDownload.forEach { listOfVideos.remove(it) }
                    return videosToDownload
                }
                return listOfVideos
            }
        }
        
        
            fun downloadVideos() {
                documentsViewModel.downloadVideos().observe(this, Observer {
                    when (it.state) {
                        WorkInfo.State.SUCCEEDED -> {
                            downloadVideos()
                        }
                        WorkInfo.State.FAILED -> {
                            // Handle error result
                        }
                    }
                })
            }
        
        class DownloadVideoWorker(
            private val context: Context,
            private val params: WorkerParameters,
            private val downloadApi: DownloadApi
        ) : CoroutineWorker(context, params) {
        
            override suspend fun doWork(): Result {
                val videos = inputData.getStringArray(VIDEOS)
                //Download videos
                return success()
            }
        
            companion object {
                const val VIDEOS: String = "VIDEOS"
            
                fun enqueue(videos: Array<String>): LiveData<WorkInfo> {
                    val downloadWorker = OneTimeWorkRequestBuilder<DownloadVideoWorker>()
                        .setInputData(Data.Builder().putStringArray(VIDEOS, videos).build())
                        .build()
                    val workManager = WorkManager.getInstance()
                    workManager.enqueue(downloadWorker)
                    return workManager.getWorkInfoByIdLiveData(downloadWorker.id)
                }
            }
        }
        
        class DownloadViewModel() : ViewModel() {
            private var listOfVideos: Array<String> // Videos urls
        
            fun downloadVideos(): LiveData<WorkInfo> {
                val videosToDownload = retrieveNextThreeVideos()
                return DownloadVideoWorker.enqueue(videos)
            }
            
            fun retrieveNextThreeVideos(): Array<String> {
                if(listOfVideos.size >= 3) {
                    val videosToDownload = listOfVideos.subList(0, 3)
                    videosToDownload.forEach { listOfVideos.remove(it) }
                    return videosToDownload
                }
                return listOfVideos
            }
        }
        
        
            fun downloadVideos() {
                documentsViewModel.downloadVideos().observe(this, Observer {
                    when (it.state) {
                        WorkInfo.State.SUCCEEDED -> {
                            downloadVideos()
                        }
                        WorkInfo.State.FAILED -> {
                            // Handle error result
                        }
                    }
                })
            }
        
        companion object {
            private val executor: ThreadPoolExecutor = Executors.newFixedThreadPool(3) as ThreadPoolExecutor
        }
        
        fun startDownloading(url: String, filePath: String) {
            downloadUtilImp.downloadQueued()
        
            runBlocking {
                downloadJob = launch(executor.asCoroutineDispatcher()) {
                    val downloadService = RetrofitInstance.api.downloadFile(url)
                    if (downloadService.isSuccessful) saveFile(downloadService.body(), filePath)
                    else downloadUtilImp.downloadFailed(downloadService.errorBody().toString())
                }
            }
        }
        
        companion object {
            private val executor: ThreadPoolExecutor = Executors.newFixedThreadPool(3) as ThreadPoolExecutor
        }
        
        fun startDownloading(url: String, filePath: String) {
            downloadUtilImp.downloadQueued()
        
            runBlocking {
                downloadJob = launch(executor.asCoroutineDispatcher()) {
                    val downloadService = RetrofitInstance.api.downloadFile(url)
                    if (downloadService.isSuccessful) saveFile(downloadService.body(), filePath)
                    else downloadUtilImp.downloadFailed(downloadService.errorBody().toString())
                }
            }
        }
        

        Xamarin app for updating apk programmatically

        copy iconCopydownload iconDownload
        Intent goToMarket = new Intent(Intent.ActionView).SetData(Uri.Parse("xxx"));
                    StartActivity(goToMarket);
        
        Intent promptInstall = new Intent(Intent.ActionView)
            .SetDataAndType(Uri.Parse("file:///path/to/your.apk"),
                            "application/vnd.android.package-archive");
        StartActivity(promptInstall);
        
        Intent goToMarket = new Intent(Intent.ActionView).SetData(Uri.Parse("xxx"));
                    StartActivity(goToMarket);
        
        Intent promptInstall = new Intent(Intent.ActionView)
            .SetDataAndType(Uri.Parse("file:///path/to/your.apk"),
                            "application/vnd.android.package-archive");
        StartActivity(promptInstall);
        

        Chrome download error when downloading file with Puppeteer

        copy iconCopydownload iconDownload
        const downloadPath = path.resolve('/my/path');
        
        await page._client.send('Page.setDownloadBehavior', {
            behavior: 'allow',
            downloadPath: downloadPath 
        });
        

        Community Discussions

        Trending Discussions on DownloadService
        • Angular 13 download file from api in entire app (.Net 6)
        • Download Many heavy files in zip. Correct implementation
        • Not able to create ZIP file through Lambda function
        • Angular / RxJs: Download Progress
        • Cannot call method in my service inside my component in Angular
        • What is the best practice for subscribe method in angular?
        • Scala compile error “value max is not a member of Int&quot;
        • How to run Jenkins with Docker on Kubernetes?
        • Downloading file using HttpClient and file-saver.js fetches JHipster app-loading page as well as requested download file
        • Queue download using Retrofit
        Trending Discussions on DownloadService

        QUESTION

        Angular 13 download file from api in entire app (.Net 6)

        Asked 2022-Feb-27 at 07:00

        I have some changes related to other thing but suddenly when i am downloading file from api

        i am getting below error

        @Injectable()
        export class FileDownloadService {
            
         constructor(private httpClient: HttpClient) { }
        
        
          public downloadFile(data: HttpResponse<Blob>) {
            const contentDisposition = data.headers.get('content-disposition');
            const filename = this.getFilenameFromContentDisposition(contentDisposition);
            const blob = data.body;
            const url = window.URL.createObjectURL(blob);
            const anchor = document.createElement("a");
            anchor.download = filename;
            anchor.href = url;
            anchor.click();
          }
        
          private getFilenameFromContentDisposition(contentDisposition: string): string {
            const regex = /filename=(?<filename>[^,;]+);/g;
            const match = regex.exec(contentDisposition);
            const filename = match.groups['filename'];
            return filename;
          }
        
        }
        

        controller:

         download() {
           
            this.dataService.download(this.fileName)
                .pipe(takeUntil(this.unsubscribe$))
                .subscribe({
                  next: (blobresponse: any) => {  
                      this.downloadService.downloadFile(blobresponse);      
                    }, error: (error:any) => { }
                });   
         }
        

        Error:

        1. ERROR TypeError: Cannot read properties of null (reading 'groups') at FileDownloadService.getFilenameFromContentDisposition (:4200/main.js:1323:32) at FileDownloadService.downloadFile (:4200/main.js:1312:31) at Object.next (:4200/src_app_views_account_account_module_ts.js:1367:38) at ConsumerObserver.next (:4200/vendor.js:90420:33) at SafeSubscriber._next (:4200/vendor.js:90389:26) at SafeSubscriber.next (:4200/vendor.js:90360:18) at :4200/vendor.js:91984:181 at OperatorSubscriber._next (:4200/vendor.js:91542:21) at OperatorSubscriber.next (:4200/vendor.js:90360:18) at subscribe.innerComplete (:4200/vendor.js:92213:28) defaultErrorLogger @ vendor.js:sourcemap:130591

        Not donwloading file entire application..I have chehcked api but response (file) is coming from api.. Please let me know what i did wrong..it is perfectly fine last week..pls suggest me i am checking from last 24 hrs. but no where find solution..

        EDIT: API response Added enter image description here

        EDIT: May be issue with contentdecoposition

        enter image description here

        ANSWER

        Answered 2022-Feb-27 at 04:00

        You have to do the null check:

        private getFilenameFromContentDisposition(contentDisposition: string): string {
            const regex = /filename=(?<filename>[^,;]+);/g;
            const match = regex.exec(contentDisposition);
            let filename = null; // or any other value you consider default
            if (typeof match !== 'undefined' && match !== null) {
                filename = match.groups['filename'];
            } 
            return filename; 
        }
        

        Source https://stackoverflow.com/questions/71281982

        Community Discussions, Code Snippets contain sources that include Stack Exchange Network

        Vulnerabilities

        No vulnerabilities reported

        Install DownloadService

        You can download it from GitHub.
        You can use DownloadService like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the DownloadService component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

        Support

        For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

        DOWNLOAD this Library from

        Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
        over 430 million Knowledge Items
        Find more libraries
        Reuse Solution Kits and Libraries Curated by Popular Use Cases
        Explore Kits

        Save this library and start creating your kit

        Explore Related Topics

        Share this Page

        share link
        Consider Popular Download Utils Libraries
        Try Top Libraries by BillKalin
        Compare Download Utils Libraries with Highest Support
        Compare Download Utils Libraries with Highest Quality
        Compare Download Utils Libraries with Highest Security
        Compare Download Utils Libraries with Permissive License
        Compare Download Utils Libraries with Highest Reuse
        Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
        over 430 million Knowledge Items
        Find more libraries
        Reuse Solution Kits and Libraries Curated by Popular Use Cases
        Explore Kits

        Save this library and start creating your kit

        • © 2022 Open Weaver Inc.