2014-06-19 1 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.

В принципе, вы получите экземпляр File из вашего files списка <input type="file"> элемента, проверьте его имя, читать его, а затем разместить его:

Complete Example (source) (кроме бита 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> 
Смежные вопросы