2016-11-08 75 views
0

我想讀取我的上傳XML文件,並從客戶端在TextArea中顯示它。我在我的JavaScript代碼中使用字符串變量而不是url。這是不正確的方式來使用網址?如果沒有,我該如何使用它?我發現大部分查詢都使用固定文件作爲url,但我的文件可以更改。這裏是我的代碼:如何使用javascript讀取上傳的xml文件?

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); 
+2

你的邏輯不是很正確。您使用'XMLHttpRequest'來調用服務器,而不是讀取客戶端上的文件。您可以使用['FileReader'](https://developer.mozilla.org/en/docs/Web/API/FileReader)直接在客戶端上使用JS讀取文件。請注意,如果您需要存儲文件,那麼您仍然必須將其上傳到您的服務器 –

+0

您能告訴我一個FileReader的示例嗎? – Mahbub

+0

這一切都在鏈接到MDN –

回答

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