js实现预览
实现文件预览的方法
在JavaScript中实现文件预览功能通常涉及读取用户上传的文件内容并在页面上展示。以下是几种常见的实现方式:
图片预览
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file.type.match('image.*')) return;
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
document.body.appendChild(img);
};
reader.readAsDataURL(file);
});
文本文件预览
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file.type.match('text.*')) return;
const reader = new FileReader();
reader.onload = function(e) {
const pre = document.createElement('pre');
pre.textContent = e.target.result;
document.body.appendChild(pre);
};
reader.readAsText(file);
});
PDF预览
需要借助PDF.js库:
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file.type !== 'application/pdf') return;
const reader = new FileReader();
reader.onload = function(e) {
const pdfData = new Uint8Array(e.target.result);
pdfjsLib.getDocument({data: pdfData}).promise.then(function(pdf) {
pdf.getPage(1).then(function(page) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const viewport = page.getViewport({scale: 1.0});
canvas.height = viewport.height;
canvas.width = viewport.width;
document.body.appendChild(canvas);
page.render({
canvasContext: context,
viewport: viewport
});
});
});
};
reader.readAsArrayBuffer(file);
});
视频/音频预览
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', function(e) {
const file = e.target.files[0];
const isMedia = file.type.match('video.*') || file.type.match('audio.*');
if (!isMedia) return;
const url = URL.createObjectURL(file);
const media = file.type.match('video.*')
? document.createElement('video')
: document.createElement('audio');
media.src = url;
media.controls = true;
document.body.appendChild(media);
});
注意事项
- 文件类型检查很重要,防止用户上传不支持的格式
- 使用URL.createObjectURL()创建的对象URL记得在不需要时调用URL.revokeObjectURL()释放内存
- 对于大文件,考虑使用流式读取或分块处理
- 不同浏览器对某些文件类型的支持可能不同,需要做好兼容性处理
以上方法可以组合使用,根据实际需求选择适合的预览方式。对于更复杂的预览需求,可能需要借助专门的库或服务。







