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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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!