Nativescript android如何将远程图像下载到设备?

时间:2017-03-17 14:43:20

标签: nativescript angular2-nativescript

任何人都可以帮我如何使用nativescript Android应用程序下载远程图像到手机? 例如,

<StackLayout>
   <Image [src]="remoteImgUrl"></Image>
   <Label tap="downloadImg({{remoteImgUrl}})" text="Download">
</StackLayout>

当用户点击“下载”时,我需要在Android设备中保存该图像。

1 个答案:

答案 0 :(得分:1)

以下是基于此应用here的示例:

打字稿

export function saveFile(res: ImageSource) {

    fileName = "some-image-name" + ".jpeg";

    var folderPath;
    if (application.android) {
        var androidDownloadsPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
        folderPath = fileSystem.path.join(androidDownloadsPath, "MyImages");
    } 

    var folder = fileSystem.Folder.fromPath(folderPath);
    var path = fileSystem.path.join(folderPath, fileName);
    var exists = fileSystem.File.exists(path);

    if (!exists) {
        var saved = res.saveToFile(path, enums.ImageFormat.jpeg);
    }

}

该方法接受imageSource作为参数,因此您可以使用fromUrl方法为imageSource调用它,例如

import * as imageSource from "image-source";
imageSource.fromUrl(IMAGE_URL_HERE)
     .then(res => {
          saveFile(res); // 
      })