Javascript HTML5 FileReader 如何返回结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11829537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 FileReader how to return result?
提问by trafalgarx
I use JS FileReader. I want to get result after file reading operation and work with this data. FileReader is asynchronous and I don't know when result is ready. How to get it done right?
我使用 JS FileReader。我想在文件读取操作后得到结果并处理这些数据。FileReader 是异步的,我不知道结果何时准备就绪。如何正确完成?
$(document).ready(function(){
$('#file_input').on('change', function(e){
var res = readFile(this.files[0]);
//my some manipulate with res
$('#output_field').text(res);
});
});
function readFile(file){
var reader = new FileReader(),
result = 'empty';
reader.onload = function(e)
{
result = e.target.result;
};
reader.readAsText(file);
//waiting until result is empty?
return result;
}
It's show "empty".
显示“空”。
How to wait until "result" is empty? Another way?
如何等到“结果”为空?其它的办法?
回答by apsillers
Reading happens asynchronously. You need to provide a custom onload
callback that defines what should happen when the read completes:
读取是异步发生的。您需要提供一个自定义onload
回调来定义读取完成时应该发生的事情:
$(document).ready(function(){
$('#file_input').on('change', function(e){
readFile(this.files[0], function(e) {
// use result in callback...
$('#output_field').text(e.target.result);
});
});
});
function readFile(file, onLoadCallback){
var reader = new FileReader();
reader.onload = onLoadCallback;
reader.readAsText(file);
}
(See the Fiddle.)
(见小提琴。)
Note that readFile
does not return a value. ?Instead, it accepts a callback function, which will fire whenever the read is done. The $('#output_field').text
operation is moved into the callback function. This ensures that that operation will not run until the reader's onload
callback fires, when e.target.result
will be filled.
请注意,readFile
不会返回值。? 相反,它接受一个回调函数,该函数将在读取完成时触发。该$('#output_field').text
操作被移入回调函数。这确保了该操作在读取器的onload
回调触发之前不会运行,何时e.target.result
将被填充。
Programming with callbacks is a bit difficult to get right at first, but it is absolutely necessary for implementing advanced functionality.
刚开始使用回调进行编程有点困难,但它对于实现高级功能是绝对必要的。
回答by Aymon Fournier
Use a Promise to wrap FileReader and then use await
to get the results:
使用 Promise 包装 FileReader ,然后使用await
获取结果:
https://blog.shovonhasan.com/using-promises-with-filereader/
https://blog.shovonhasan.com/using-promises-with-filereader/
回答by Aymon Fournier
Here's the javascript:
这是javascript:
$(document).ready(function() {
$('#file_input').on('change', function(e) {
function updateProgress(evt) {
if (evt.lengthComputable) {
// evt.loaded and evt.total are ProgressEvent properties
var loaded = (evt.loaded / evt.total);
if (loaded < 1) {
// Increase the prog bar length
style.width = (loaded * 200) + "px";
}
}
}
function loaded(evt) {
// Obtain the read file data
var fileString = evt.target.result;
// Handle UTF-16 file dump
$('#output_field').text(fileString);
}
var res = readFile(this.files[0]);
var reader = new FileReader();
reader.readAsText(this.files[0], "UTF-8");
reader.onprogress = updateProgress;
reader.onload = loaded;
});
});
function readFile(file) {
var reader = new FileReader(),
result = 'empty';
reader.onload = function(e) {
result = e.target.result;
};
reader.readAsText(file);
return result;
}
And of course, the HTML portion:
当然,还有 HTML 部分:
<input type="file" id="file_input" class="foo" />
<div id="progBar" style="background-color:black;width:1px;"> </div>
<div id="output_field" class="foo"></div>
Seems to work for *.txt files.
似乎适用于 *.txt 文件。
回答by websky
use case FileReader
用例 FileReader
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
<a href="#" id="viewSource">Source file</a>
</body>
</html>