windows 8 商店 javascript 应用程序,从网络下载并保存图像

windows 8 store javascript app, download and save images from web

我有一个要求,我必须从网上下载图片 url 并将它们保存到图片库中的一些文件夹中。请注意,它是一个 jabvascript 应用程序 (winJS)。我尝试了一些示例,但没有成功。

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

方法一:

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

方法二:

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

              });

           });
    }

这里是您的操作方法(并且不要忘记在您的清单中声明访问图片库的能力):

function downloadFileAsync(targetUrl , fileName) {
      return  WinJS.xhr({
            responseType: "blob",
            type: "GET",
            url: targetUrl,
        }).then(function (response) {
            var fileContents = response.response;
            return Windows.Storage.KnownFolders.picturesLibrary.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) {
                return newFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (stream) {
                    return Windows.Storage.Streams.RandomAccessStream.copyAsync(fileContents.msDetachStream(), stream).then(function () {
                        return stream.flushAsync().then(function () {
                            stream.close();
                            fileContents.msClose();
                        });
                    });
                });
            });
        }); 
}