Download files with angular2 - ionic 2

纵然是瞬间 提交于 2019-12-01 23:47:06

My problem was that soundcloud returned a response with redirect. I had to detect the redirect state and manually redirect to the response.headers.Location

That is the working code:

public download(localAudio: LocalAudio): void {
    let fileName: string = localAudio.id + '.mp3';

    var audio: StorageAudio = {
        localAudio: localAudio,
        url: `https://api.soundcloud.com/tracks/${localAudio.id}/download?client_id=${this.SC_CLIENT_ID}`,
        fileName: fileName,
        filePath: this.file.dataDirectory + fileName
    };

    if (this.platform.is('ios')) {
        audio.filePath = audio.filePath.replace(/^file:\/\//, '');
    }

    this.toastNotifications.showStartingDownloadMsg();

    this.http.downloadFile(audio.url, {}, {}, audio.filePath).then(response => {
        this.toastNotifications.showDownloadCompleteMsg();

        this.storeAudioInformation(audio);
    }).catch(response => {
        /**
         * Handle redirects if exist.
         */
        if (this.hasRedirection(response)) {
            console.log("Redirect to " + response.headers.Location);
            audio.url = response.headers.Location;

            this.redirectToDownload(audio);
        } else {
            this.toastNotifications.showDownloadErrorMsg();
        }
    });
}

public hasRedirection(response: any): boolean {
    return (response.headers.Location && (response.status === 301 || response.status === 302));
}

public redirectToDownload(audio: StorageAudio): void {
    this.http.downloadFile(audio.url, {}, {}, audio.filePath).then(response => {
        this.toastNotifications.showDownloadCompleteMsg();

        this.storeAudioInformation(audio);
    }).catch(response => {
        console.log("Error catch: " + JSON.stringify(response));
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!