Blob URL
2024年07月05日
一、认识
二、实现
2.1 Video
<input type="file" accept="video/*" />
<script>
function handleFileSelect(evt) {
const file = evt.target.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
const videoBlob = new Blob([e.target.result], { type: file.type });
const blobUrl = URL.createObjectURL(videoBlob);
const video = document.createElement("video");
video.src = blobUrl;
video.controls = true;
document.body.appendChild(video);
};
}
const inputEl = document.querySelector("input");
inputEl.addEventListener("change", handleFileSelect);
</script>
2.2 Image
<input type="file" accept="image/*" />
<script>
function handleFileSelect(evt) {
const file = evt.target.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
const imgBlob = new Blob([e.target.result], { type: file.type });
const blobUrl = URL.createObjectURL(videoBlob);
const img = document.createElement("img");
img.src = blobUrl;
img.controls = true;
document.body.appendChild(img);
};
}
const inputEl = document.querySelector("input");
inputEl.addEventListener("change", handleFileSelect);
</script>