Download file using WinJS.xhr

Snippet to download a file using WinJS.xhr and save it. The file variable below is a StorageFile, result of pickSaveFileAsync.

Note the usage of responseType: “blob” as an option to xhr, and how it is copied to the file stream with msDetachStream.

WinJS.xhr({
    responseType: "blob",
    type: "GET",
    url: "http://example.com/",
}).then(function (response) {
    var fileContents = response.response;

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

I tried to use replaceWithStreamedFileFromUriAsync and writeBufferAsync, but never managed to make it work. If you do, leave a comment!


Posted

in

by

Tags: