2014-06-19 16 views
-1

我有一個HTML表單來上傳文件。使用javascript獲取文件作爲字符串

我的目標是提交表單,檢查文件是否具有XML擴展名,並將該文件作爲字符串獲取到JavaScript變量中。

然後,我想使用此字符串向服務器發送POST請求。

任何想法我可以做到這一點?

+1

@Dalorzo:是的,你可以([更多](http://stackoverflow.com/questions/3146483/html5-file-api-read-as-text-and-二進制/ 3146509#3146509))。但我不認爲OP真的想要。 –

+0

@ user:你說你在「提交」表單,並且你想把表單的數據放入一個JavaScript變量中。你在服務器上使用JavaScript嗎? –

+3

爲了便於說明,您希望將文件上傳到服務器,將文件中的數據從服務器發送到客戶端,然後將數據從客戶端發回服務器?我不確定你的主要目標是什麼,但我認爲你的方法可能會關閉。 – Smeegs

回答

1

我的目標是提交表單,檢查文件是否具有XML擴展名,並將該文件作爲字符串獲取到JavaScript變量中。

我不認爲你真的想要在這個階段提交表單(如在發送到服務器)。

然後,我想發送一個POST請求到服務器使用這個字符串。

你可以做到這一點在支持File API,這是most modern ones但不是IE8或IE9瀏覽器。有一個例子in this answer

基本上,你從你的<input type="file">元素的files名單得到File例如,檢查它的名字,讀它,然後將它張貼:

Complete Examplesource(比POST位,我想你等知道該怎麼做)

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Example</title> 
</head> 
<body> 
    <input type="file"> 
    <button>Go</button> 
<script> 
    (function() { 
    "use strict"; 

    // Get our input element and our button; in this example there's 
    // just one of each, you'd narrow down these selectors of course 
    var inputElement = document.querySelector("input[type=file]"), 
     button = document.querySelector("button"); 

    if (typeof FileReader !== 'function') { 
     alert("The file API isn't supported on this browser."); 
     inputElement.style.display = button.style.display = "none"; 
     return; 
    } 
    if (!inputElement.files) { 
     alert("Odd, this browser has FileReader but no `files` property on the input element."); 
     inputElement.style.display = button.style.display = "none"; 
     return; 
    } 

    button.addEventListener("click", function() { 
     var file, filename, reader, filedata; 

     // Does it have any files? 
     if (inputElement.files.length === 0) { 
     alert("No file chosen"); 
     return; 
     } 

     // Get its first file 
     file = inputElement.files[0]; 

     // Get its name in lower case 
     filename = file.name.toLowerCase(); 

     // XML extension? 
     if (filename.substr(-4) !== ".xml") { 
     alert("Please only choose .xml files"); 
     } 
     else { 
     // Yes, read it 
     reader = new FileReader(); 
     reader.onload = function() { 
      // Get the file data, note that this happens asynchronously 
      filedata = reader.result; 
      // Send your POST with the data; here, we'll just dump it out 
      // as text 
      displayXml(filedata); 
     }; 
     reader.readAsText(file); // or you can use readAsBinaryString 
     } 
    }, false); 

    function displayXml(xmlText) { 
     var pre = document.createElement('pre'); 
     pre.innerHTML = xmlText.replace(/&/g, "&amp;").replace(/</g, "&lt;"); 
     document.body.appendChild(pre); 
    } 
    })(); 
</script> 
</body> 
</html>