I want to read the text content from that input. I tried this: var fileInput " /> I want to read the text content from that input. I tried this: var fileInput " /> I want to read the text content from that input. I tried this: var fileInput "/>

WinJS UWP javascript - how to read a file through a file input

247 Views Asked by At

In my HTML, I have this input:

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

I want to read the text content from that input. I tried this:

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

But I got JavaScript runtime error: Type mismatch

Wondering how I can fix this

1

There are 1 best solutions below

3
Nico Zhu On

Please use FileOpenPicker to get StorageFile in uwp avoid above issue.

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