Search code examples
javascriptwindows-8winjsfileapistoragefile

How to get a standard JavaScript File API object using the Windows.Storage FileOpenPicker class?


While working on a Windows 8 app, I noticed that I can open and get a reference to a File object using something like:

// Markup
<input type='file' id='myfile'/>

// JavaScript
var fInput = document.getElementById('myFile');
fInput.onchange = function (e) {
    var dataSource = e.target;
    var file = dataSource.files[0]; // object of type 'File'
}

However I would like to present the user with a file picker without the need to press the 'Browse' button. So I tried using the FilePicker class like this:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.pickSingleFileAsync().then(function (file) {
    // in this case, file is a 'StorageFile' object
});

So the question is, can pickSingleFileAsync somehow return a File object instead of StorageFile ?


Solution

  • Use MSApp.createFileFromStorageFile. Ignore the documentation error here. It tells the reverse of what the api does.

    // TODO - more code is required here to initialize file open picker. 
    // refer the file picker sample
    var picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.pickSingleFileAsync().then(function (storageFile) {
        // ignore when file pick is cancelled
        if (!storageFile)
            return;
        var file = MSApp.createFileFromStorageFile(storageFile);
    });