客户端文本文件验证和上传

时间:2022-12-09 09:56:20

I'm trying to upload a file into the browser and access it using JavaScript. Is this possible? I've looked around and it seems that you can accomplish this using flash. I was trying to see if there was an HTML5/pure JavaScript solution.

我正在尝试将文件上传到浏览器并使用JavaScript访问它。这可能吗?我环顾四周,似乎你可以使用闪光灯完成这个任务。我试图看看是否有HTML5 /纯JavaScript解决方案。

I'm trying to upload a CSV file (each row contains a possible database entry) and validate it on the fly using javascript. If it passes validation, then I'll send a POST to the server to create the items.

我正在尝试上传CSV文件(每行包含一个可能的数据库条目)并使用javascript动态验证它。如果它通过验证,那么我将向服务器发送POST以创建项目。

1 个解决方案

#1


8  

This is possible. MDN offers a detailed explanation on this.

这个有可能。 MDN对此进行了详细说明。

The following is a basic method to read a text file using the FileReader API:
  http://jsfiddle.net/tGpDG/

以下是使用FileReader API读取文本文件的基本方法:http://jsfiddle.net/tGpDG/

<input type="file" id="file_upload">
<script>
var input_file = document.getElementById('file_upload');
input_file.onchange = function() {
    var file = this.files[0];
    // Do something with the FileReader object
    var reader = new FileReader();  
    reader.onload = function(ev) {
        // Show content  (ev.target === reader)
        alert(ev.target.result);
    };
    // Read as plain text
    reader.readAsText(file);  
};
</script>

#1


8  

This is possible. MDN offers a detailed explanation on this.

这个有可能。 MDN对此进行了详细说明。

The following is a basic method to read a text file using the FileReader API:
  http://jsfiddle.net/tGpDG/

以下是使用FileReader API读取文本文件的基本方法:http://jsfiddle.net/tGpDG/

<input type="file" id="file_upload">
<script>
var input_file = document.getElementById('file_upload');
input_file.onchange = function() {
    var file = this.files[0];
    // Do something with the FileReader object
    var reader = new FileReader();  
    reader.onload = function(ev) {
        // Show content  (ev.target === reader)
        alert(ev.target.result);
    };
    // Read as plain text
    reader.readAsText(file);  
};
</script>