WinJS UWP javascript - 如何通过文件输入读取文件

Posted

技术标签:

【中文标题】WinJS UWP javascript - 如何通过文件输入读取文件【英文标题】:WinJS UWP javascript - how to read a file through a file input 【发布时间】:2019-12-20 19:03:35 【问题描述】:

在我的 html 中,我有这样的输入:

<input type="file" id="csv_file_input" />

我想从该输入中读取文本内容。我试过这个:

                var fileInput = $('#csv_file_input');
                var file = fileInput[0].files[0];
                Windows.Storage.FileIO.readTextAsync(file)
                        .then(function(text) 
                            console.log(text);
                        );

但我得到了javascript runtime error: Type mismatch

想知道如何解决这个问题

【问题讨论】:

【参考方案1】:

请在uwp中使用FileOpenPicker获取StorageFile,避免上述问题。

var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
// Users expect to have a filtered view of their folders depending on the scenario.
// For example, when choosing a documents folder, restrict the filetypes to documents for your application.
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg",".txt"]);

// Open the picker for the user to pick a file
openPicker.pickSingleFileAsync().then(function (file) 
    if (file) 
        // Application now has read/write access to the picked file
        WinJS.log && WinJS.log("Picked photo: " + file.name, "sample", "status");
        Windows.Storage.FileIO.readTextAsync(file).done(function (fileContent) 
            WinJS.log && WinJS.log("The following text was read from '" + SdkSample.sampleFile.name + "':\n" + fileContent, "sample", "status");
        ,
            function (error) 
                if (error.number === SdkSample.E_NO_UNICODE_TRANSLATION) 
                    WinJS.log && WinJS.log("File cannot be decoded as Unicode.", "sample", "error");
                 else 
                    WinJS.log && WinJS.log(error, "sample", "error");
                
            );

     else 
        // The picker was dismissed with no selected file
        WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
    
);

【讨论】:

有没有办法让这个界面使用拖放功能? 我不认为该链接可以达到我想要的效果。无论如何,它适用于 c#/xaml,而不适用于 javascript/html 我想你可以创建一个新线程来描述你想要的,我会检查的。

以上是关于WinJS UWP javascript - 如何通过文件输入读取文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 UWP 应用(C# 或 WinJS)中获取 Windows 10 版本(例如 1809、1903、1909、...)?

WinJS 4.0兼容AngularJSReactBootstrap和Knockout

默认情况下如何以全屏模式启动 uwp webview 应用程序

Win10系列:JavaScript 模板绑定

WinJS 中的 System.Text.Encoding

Win10系列:JavaScript页内导航