URL.createObjectURL 打开html
时间: 2023-09-04 15:11:50 浏览: 41
URL.createObjectURL 方法可以用来生成一个 Blob URL,可以将其用作图片、音频、视频等文件的 URL。在 HTML 中,可以通过创建一个链接或使用 video、audio 或者 img 等标签来打开该 URL。下面是一个示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用 URL.createObjectURL 打开文件</title>
</head>
<body>
<input type="file" id="fileInput">
<br><br>
<img id="imgPreview" src="" alt="预览图">
<script>
const fileInput = document.getElementById('fileInput');
const imgPreview = document.getElementById('imgPreview');
fileInput.addEventListener('change', () => {
const file = fileInput.files[0];
if (file) {
const blobUrl = URL.createObjectURL(file);
imgPreview.src = blobUrl;
}
});
</script>
</body>
</html>
```
该示例代码包含一个文件选择框和一个用于显示文件预览的图像标签。当选择一个文件后,使用 URL.createObjectURL 方法生成该文件的 Blob URL,并将其赋值给图像标签的 src 属性,从而显示该文件的预览图像。