Windows 8存储javascript应用程序,从网上下载并保存图像

时间:2015-11-23 11:01:13

标签: javascript jquery windows-runtime windows-store-apps winjs

我有一个要求,我必须从网址下载图像并将其保存到图片库中的某些文件夹。请注意,它是一个jabvascript应用程序(winJS)。我尝试了一些例子但没有运气。

下面是我试过的一些代码:

方法1:

var download = null;
var promise = null;
function DownloadFile(uriString, fileName) {
    try {
        // Asynchronously create the file in the pictures folder.
        Windows.Storage.KnownFolders.picturesLibrary.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (newFile) {
            var uri = Windows.Foundation.Uri(uriString);
            var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();

            // Create a new download operation.
            download = downloader.createDownload(uri, newFile).startAsync().then(complete, error, progress);

            // Start the download and persist the promise to be able to cancel the download.
            promise = download.startAsync().then(complete, error, progress);
        }, error);
    } catch (err) {
        // displayException(err);
    }
};

方法2:

    function downloadFile(uri) {
 var localFolder = Windows.Storage.KnownFolders.picturesLibrary;
     var thumbnail = Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(Windows.Foundation.Uri(uri));
        Windows.Storage.StorageFile.createStreamedFileFromUriAsync("photo.jpg", Windows.Foundation.Uri(uri), thumbnail).done(function (newFile) {
            /* Your success and error handlers */

            localFolder.createFileAsync("photo2.jpg", Windows.Storage.CreationCollisionOption.replaceExisting)
              .then(function (file) {
                  newFile.copyAndReplaceAsync(file);

              });

           });
    }

0 个答案:

没有答案