用于将blob或类型为file的input元素或拖拽事件产生的file用作图片的src:
参数是blob(例如返回类型为blob的ajax请求返回的)
<!DOCTYPE html>
<html lang="en">
<body>
<img id="img" alt="">
<script>
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", 'https://laravel.gign.xyz/cxk.jpg', true);
xhr.responseType = "blob"
xhr.onload = function () {
if (this.status == 200) {
let blob = this.response
let img = document.getElementById("img")
img.src = window.URL.createObjectURL(blob)
img.onload = e => window.URL.revokeObjectURL(img.src)
}
}
xhr.send()
</script>
</body>
</html>
参数是file
<!DOCTYPE html>
<html lang="en">
<body>
<img id="img" width="320px" alt="">
<div name="image" id="dropbox" style="min-width:300px;min-height:200px;border:3px dashed silver;"></div>
<script>
// 目标元素中dragover和drop事件中要阻止默认行为(拒绝被拖放),否则拖放不能被实现
dropbox.addEventListener("dragover", function (e) {
e.preventDefault();
});
dropbox.addEventListener("drop", function (e) {
e.preventDefault();
let file = e.dataTransfer.files[0]
img.onload = () => {
window.URL.revokeObjectURL(img.src)
}
img.src = window.URL.createObjectURL(file)
});
</script>
</body>
</html>
网友评论