使用angular2 - ionic 2下载文件 [英] Download files with angular2 - ionic 2

查看:119
本文介绍了使用angular2 - ionic 2下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ionic 2应用程序,我需要从soundcloud下载音频。我已经有了我需要做的请求的网址:

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.com/tracks/${audio.id}/download?client_id=${this.SC_CLIENT_ID}`

我想知道怎么做。我尝试使用FileTransfer:

I want to know how to do this. I tryed with FileTransfer:

public download(audio: any): void {

        this.platform.ready().then(() => {
            console.log("Clickeo para descargar: " + audio.id);

            let url = `https://api.soundcloud.com/tracks/${audio.id}/download?client_id=${this.SC_CLIENT_ID}`;

            let pathToSaveTo: string = '';

            if (this.platform.is('android')) {
                pathToSaveTo = cordova.file.externalApplicationStorageDirectory + audio.id + '.wav';

                let fileTransfer = new Transfer();

                fileTransfer.onProgress(this.onProgress);

                fileTransfer.download(url, pathToSaveTo)
                    .then((entry) => {
                        console.log('download complete: ' + entry.toURL());
                    }, (error) => {

                        let prompt = this.alertCtrl.create({
                            title: 'Error',
                            subTitle: error,
                            buttons: ['Accept']
                        });

                        prompt.present();
                    });
            }
        });

    }

    onProgress = (progressEvent: ProgressEvent) : void => {
        this.ngZone.run(() => {
            if (progressEvent.lengthComputable) {
                let progress: any = Math.round((progressEvent.loaded / progressEvent.total) * 100);
                console.log(progress);
                let toast = this.toastCtrl.create({
                  message: progress,
                  duration: 100
                });
                toast.present();
            }
        });
    }

但它总是下载零KB文件。有解决方案吗也许angular2方式,或者我做错了?
如果我把这个网址放在浏览器中,使用正确的音频ID和mi客户端ID,就会开始下载,但不能使用FileTransfer。

But it always download a zero KB file. Any solution? Maybe angular2 way, or I'm doing it wrong? If I put this url in browser, with the properly audio id and mi client id, it starts to download, but not with FileTransfer.

非常感谢提前。

Ivan。

推荐答案

我的问题是声音云通过重定向返回响应。我必须检测重定向状态并手动重定向到 response.headers.Location

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

这是工作代码:

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));
    });
}

这篇关于使用angular2 - ionic 2下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆