如何使用javascript阅读上传的xml文件?

时间:2016-11-08 14:10:24

标签: javascript xml

我想阅读我上传的xml文件,并在客户端的TextArea中显示它。我在我的javascript代码中遇到问题,我在使用字符串变量而不是url。使用网址不正确吗?如果没有,我该如何使用它?大多数查询我发现他们使用固定文件作为url,但我的文件可以更改。这是我的代码:

function fillTextArea() {
    var text = document.getElementById("connectionName").value;
    document.getElementById("recentDevices").value += text + '\n';
    var filename = $('input[type=file]').val().split('\\').pop();
    var xml = new XMLHttpRequest();
    xml.open('Get', filename, false);
    xml.send();
    var xmlData = xml.responseXML;
    document.getElementById("xmlFileInfo").value += xmlData;
}
<div class="row">
    <div class="col-md-6">
        <div class="input-group">
            <div class="input-group">
                <span class="input-group-addon" id="basic-addon1">Connect To:</span>
                <input type="text" class="form-control" id="connectionName" name="connectionName" placeholder="Name" aria-describedby="basic-addon1">
            </div>
            <table>
                &nbsp; &nbsp;
                <tr>
                    <td>Upload XML File</td>
                    <td><input type="file" name="xmlFile" id="xmlFile" accept=".xml" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" value="upload" class="btn btn-primary" onClick="fillTextArea()" /></td>
                </tr>
            </table>
        </div>
    </div>
    <div class="col-md-6">
        <div class="panel panel-info">
            <div class="panel-heading">
                <h3 class="panel-title">Recent Machines</h3>
            </div>
            @Html.TextArea("Xml File Information", new { id = "xmlFileInfo", style = "max-width:100%; min-height:250px", @class = "form-control" })
        </div>
        <div class="panel panel-info">
            <div class="panel-heading">
                <h3 class="panel-title">Recent Devices</h3>
            </div>
            @Html.TextArea("Recent Devices", new { id = "recentDevices", style = "max-width:100%; min-height:250px", @class = "form-control" })
        </div>
    </div>
</div>

我认为我的代码在下面的这一行中存在问题,

xml.open('Get', filename, false);

1 个答案:

答案 0 :(得分:0)

我修改了我的javascript代码并获得了另一种成功显示它的方法。谢谢@Rory McCrossan。这是我修改过的Javascript代码部分,

    window.onload = function () {
    var fileInput = document.getElementById('xmlFile');
    var fileDisplayArea = document.getElementById('xmlFileInfo');

    fileInput.addEventListener('change', function (e) {
        var file = fileInput.files[0];
        var textType = /text.*/;

        if (file.type.match(textType)) {
            var reader = new FileReader();

            reader.onload = function (e) {
                xmlFileInfo.innerText = reader.result;
            }

            reader.readAsText(file);
        } else {
            xmlFileInfo.innerText = "File not supported!"
        }
    });