单个文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<!-- multiple 此时多选 -->
<input type="file" id="file" onchange="getInfo(this)">
<script>
var myfile = document.getElementById('file')
var con = document.getElementById('content')
function getInfo(node) {
var file = node.files[0]
// 创建一个文件对象
var fr = new FileReader()
// 读取文件,返回url
fr.readAsDataURL(node.files[0])
// 读取文件,返回内容
// fr.readAsText(node.files[0])
// 监听读取成功
fr.onload = function(e) {
con.innerHTML = "<img src="+ e.target.result +">"
console.log('返回结果', e.target.result)
}
}
</script>
</body>
</html>
单文件上传之-window.URL.createObjectURL()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<!-- multiple 此时多选 -->
<input type="file" id="file" onchange="getInfo(this)">
<script>
// var myfile = document.getElementById('file')
var con = document.getElementById('content')
function getInfo(node) {
var url = window.URL.createObjectURL(node.files[0])
con.innerHTML = "<img src="+ url +">"
}
</script>
</body>
</html>
多文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<!-- multiple 此时多选 -->
<input type="file" multiple id="file" onchange="getInfo(this)">
<script>
var n = 0; // 当前上传图片的索引,即需要加载第几个
var len; // 上传文件的数量
var fr = new FileReader()
var con = document.getElementById('content')
var fileObj = document.getElementById('file')
fr.onload = function(e) {
if (e.target.result) {
var str = '<img src="'+ e.target.result +'" />'
con.innerHTML += str
n++
if (n < len) {
readFiles(n)
}
}
}
function readFiles(n) {
fr.readAsDataURL(fileObj.files[n])
}
function getInfo() {
n = 0
len = fileObj.files.length
readFiles(n)
}
</script>
</body>
</html>