Search code examples
javascriptjquerywindows-runtimewindows-store-appswinjs

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


I have a requirement where i have to download the images from the web url and save them to some folders in picture library. note that it is an jabvascript app (winJS). I tried some of the examples and had no luck.

below are some of the codes i tried:

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

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

              });

           });
    }

Solution

  • Here how you can do (and don't forget to declare in your manifest the capability to access to the picture library):

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