Download files with angular2 - ionic 2

前端 未结 1 1257
温柔的废话
温柔的废话 2021-01-20 08:45

I have an Ionic 2 app, and I need to download audios from soundcloud. I already have the url that I need to do the request:

let url = `https://api.soundcloud         


        
相关标签:
1条回答
  • 2021-01-20 08:59

    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));
        });
    }
    
    0 讨论(0)
提交回复
热议问题