windows8存储javascript应用程序,从web下载和保存图像

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

本文关键字:web 下载和 保存 图像 存储 javascript 应用程序 windows8      更新时间:2023-09-26

我有一个要求,我必须从web url下载图像,并将它们保存到图片库中的一些文件夹中。请注意,它是一个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);
              });
           });
    }

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

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