实现这功能是用到 window.URL 对象
1. window.URL 是干什么的
window对象的URL对象是专门用来将blob或者file读取成一个url的。
例: 将file、blob对象转化为url
var url = window.URL.createObjectURL(file / blob)
- 这个url可以用在html的任何可以使用url的地方,比如img的src ; audio/video的src和source标签等。
- 这些file或blob可以是在本地硬盘中通过选择的文件,也可以是通过ajax请求后某个不知名的服务器请求到内存的。
2. URL构造函数将普通url转换成URL对象
除了可以将一个文件或者blob转化成一个URL对象,还可以将一个url字符串转换成一个URL对象
var parsedUrl = new URL('https://www.baidu.com?id=123v');
输出url请求中的id字段
console.log(parsedUrl.searchParams.get("id"));
// 123v
给这个url请求增加name字段,然后输出这个url
parsedUrl.searchParams.set("name" , 'xiaoming')
console.log(parsedUrl.toString());
// https://www.baidu.com/?id=123v&name=xiaoming
3. URL实例对象的toString()方法
URL的toString()方法可以将URL转换成url字符串,且:
URL.toString() <==> URL.href
let url = new URL('http://www.baidu.com')
console.log(url.toString()==url.href);
// true
4. URL对象静态方法createObjectURL(object)
URL.createObjectURL(object)是URL 对象的静态方法,用于创建一个DOMString(is a UTF-16 string),其实就是
返回了一个在内存中指向传入参数object的引用路径url字符串。生成的这个url字符串会在当前页面的document被销毁的时候失效。
objectURL = URL.createObjectURL(object);
// object
// A File, Blob or MediaSource object to create an object URL for.
// return
// A DOMString containing an object URL that can be used to reference the contents of the specified source object.
5. 应用示例
demo.html 实时预览上传的图片
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>图片预览</title>
<script src="js/jquery-3.3.1.min.js"></script>
<style>
.img {
border: 1px, red, solid;
height: 450px;
width: 800px;
}
</style>
</head>
<body>
<input type="file" name="" value="" id="file">
<div class="img">
<img src="" alt="" height="100%" width="100%" id='img'>
</div>
</body>
<script type="text/javascript">
$('#file').change(function(){
console.log(this); // 打印这个input对象
console.log(this.files[0]); // 打印input对象的第一个文件
var srcs = window.URL.createObjectURL(this.files[0]); //获取路径
$('#img').attr("src", srcs); //展示图片
});
</script>
</html>