JSFiddle - React, Tailwind, and code Playground
by tu genhua
HTML
<h1 style="color:red;font-size:24px;">文件选择如下:</h1>
<div>
<label>请选择一个图片:</label>
<input type = "file" id = "file" accept="image/*"/>
<div style="height:50px;"></div>
<div><input type="button" value="读取图像" id="readImage" />
<input type="button" value="读取二进制数据" id="readBinary" />
<input type="button" value="读取文本文件" id="readText" /></div>
</div>
<div id="result"></div>
JavaScript
// 将文件以Data URL形式读入页面
function readAsDataURL() {
// 检查是否为图像文件
var file = document.getElementById("file").files[0];
var reader = new FileReader();
// 将文件以data url 形式读入页面
reader.readAsDataURL(file);
reader.onload = function(e) {
var result = document.getElementById("result");
// 在页面上显示文件
$("#result").html("<img src = '"+this.result+"' alt=''/>");
}
}
// 将文件以二进制形式进行读入页面
function readAsBinaryString() {
var file = document.getElementById("file").files[0];
var reader = new FileReader();
// 将文件以二进制形式读入页面
reader.readAsBinaryString(file);
reader.onload = function(f) {
var result = document.getElementById("result");
$("#result").html(this.result);
}
}
// 将文件以文本形式进行读入页面
function readAsText() {
var file = document.getElementById("file").files[0];
var reader = new FileReader();
// 将文件以文本形式读入页面
reader.readAsText(file);
reader.onload = function(f) {
var result = document.getElementById("result");
$("#result").html(this.result);
}
}
$("#readImage").click(function(){
readAsDataURL();
});
$("#readBinary").click(function(){
readAsBinaryString();
});
$("#readText").click(function(){
readAsText();
});