是否可以上传一个文本文件输入HTML / JS? [英] Is it possible to upload a text file to input in HTML/JS?
问题描述
我在HTML表单中有一些输入框,当表单加载时需要更新,这些值需要从文本文件上传。
这里也提到了一个类似的问题:
上传文本文件以在HTML / JS中输入
我在网上搜索了这个,但找不到任何正确的答案。
所以我想知道它是否可行?
如果你想走客户端路线,您会对HTML5 FileReader API感兴趣。不幸的是,目前没有广泛的浏览器支持,因此您可能需要考虑谁将使用该功能。我认为可以使用最新的Chrome和Firefox。
这里有一个实际的例子: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
我也在这里阅读以找到 readAsText
方法: http://www.w3.org/TR/file-upload/#dfn-readAsText
我会做这样的事情(为简洁起见,jQuery): http://jsfiddle.net/AjaDT/ 2 /
Javascript
var fileInput = $ ( '#files');
var uploadButton = $('#upload');
$ b $ uploadButton.on('click',function(){
if(!window.FileReader){
alert('Your browser is supported');
返回false;
}
var input = fileInput.get(0);
//创建一个reader对象
var reader = new FileReader();
if(input.files.length){
var textFile = input.files [0];
//读取文件
reader.readAsText(textFile);
//当它被加载时,处理它
$(reader).on('load',processFile);
} else {
alert('请在继续之前上传文件')
}
});
函数processFile(e){
var file = e.target.result,
results;
if(file& file.length){
results = file.split(\\\
);
$('#name')。val(results [0]);
$('#age')。val(results [1]);
$ b $文本文件
Jon
25
I have some input boxes in a HTML form that need to be updated when the form loads and these values need to be uploaded from a text file.
A similar question was also asked here:
Uploading Text File to Input in Html/JS
I have searched for this on the internet, but couldn't find any correct answer.
So I want to know whether it is possible or not?
解决方案 If you wish to go the client side route, you'll be interested in the HTML5 FileReader API. Unfortunately, there is not wide browser support for this, so you may want to consider who will be using the functionality. Works in latest Chrome and Firefox, I think.
Here's a practical example: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
And I also read here to find the readAsText
method: http://www.w3.org/TR/file-upload/#dfn-readAsText
I would do something like this (jQuery for brevity): http://jsfiddle.net/AjaDT/2/
Javascript
var fileInput = $('#files');
var uploadButton = $('#upload');
uploadButton.on('click', function() {
if (!window.FileReader) {
alert('Your browser is not supported');
return false;
}
var input = fileInput.get(0);
// Create a reader object
var reader = new FileReader();
if (input.files.length) {
var textFile = input.files[0];
// Read the file
reader.readAsText(textFile);
// When it's loaded, process it
$(reader).on('load', processFile);
} else {
alert('Please upload a file before continuing')
}
});
function processFile(e) {
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
$('#name').val(results[0]);
$('#age').val(results[1]);
}
}
Text file
Jon
25
这篇关于是否可以上传一个文本文件输入HTML / JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!