如何使用Windows.Storage FileOpenPicker类获取标准JavaScript文件API对象?

时间:2013-05-29 21:46:09

标签: javascript windows-8 winjs fileapi storagefile

在使用Windows 8应用程序时,我注意到我可以使用以下内容打开并获取对File对象的引用:

// 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'
}

但是,我想向用户提供文件选择器,而无需按“浏览”按钮。所以我尝试使用FilePicker类:​​

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

所以问题是,pickSingleFileAsync能否以某种方式返回File个对象而不是StorageFile

1 个答案:

答案 0 :(得分:1)

使用MSApp.createFileFromStorageFile。在此处忽略文档错误。它告诉了api的反面。

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