我正在尝试使用FileReader(),JavaScript。
获取文件内容我找到了这个答案:https://stackoverflow.com/a/21962101/2898694
正如@Markasoftware在评论中所说,我试图将结果保存到var。
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var myFile = evt.target.files[0];
var reader = new FileReader();
var result;
reader.readAsText(myFile);
reader.onload=function(){
result = reader.result;
console.log(result); // works
}
console.log(result); // not works
}
如果我试图查看onload
处理程序中的内容一切正常,但是从中我看不到结果。为什么呢?
答案 0 :(得分:0)
因为onload运行asynchrone。在onload事件被触发之前执行console.log(result); // not works
。
更多相关内容:How do I return the response from an asynchronous call?
答案 1 :(得分:0)
示例强>
<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>