纯前端 文件预览方法汇总

crary,记忆 2024-06-29 11:03:02 阅读 53

        以下是通过javaScript的方法实现文件预览的方法汇总:

1.使用HTML5的File API和Canvas来预览图片文件:

<!DOCTYPE html>

<html>

<head>

<title>Image Preview</title>

</head>

<body>

<input type="file" id="fileInput">

<img id="previewImage">

<script>

document.getElementById('fileInput').addEventListener('change', function() {

var file = this.files[0];

var reader = new FileReader();

reader.onload = function(e) {

document.getElementById('previewImage').src = e.target.result;

};

reader.readAsDataURL(file);

});

</script>

</body>

</html>

2.使用HTML5的File API和Video标签来预览视频文件:

<!DOCTYPE html>

<html>

<head>

<title>Video Preview</title>

</head>

<body>

<input type="file" id="fileInput">

<video id="previewVideo" controls></video>

<script>

document.getElementById('fileInput').addEventListener('change', function() {

var file = this.files[0];

var reader = new FileReader();

reader.onload = function(e) {

document.getElementById('previewVideo').src = e.target.result;

};

reader.readAsDataURL(file);

});

</script>

</body>

</html>

3.使用第三方库如PDF.js来预览PDF文件:

<!DOCTYPE html>

<html>

<head>

<title>PDF Preview</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.8.335/pdf.min.js"></script>

</head>

<body>

<input type="file" id="fileInput">

<iframe id="previewPDF" width="100%" height="500px"></iframe>

<script>

document.getElementById('fileInput').addEventListener('change', function() {

var file = this.files[0];

var reader = new FileReader();

reader.onload = function(e) {

var fileData = new Uint8Array(e.target.result);

pdfjsLib.getDocument({data: fileData}).promise.then(function(pdf) {

pdf.getPage(1).then(function(page) {

var scale = 1.5;

var viewport = page.getViewport({ scale: scale });

var canvas = document.createElement('canvas');

var context = canvas.getContext('2d');

canvas.height = viewport.height;

canvas.width = viewport.width;

var renderContext = {

canvasContext: context,

viewport: viewport

};

page.render(renderContext).promise.then(function() {

document.getElementById('previewPDF').src = canvas.toDataURL();

});

});

});

};

reader.readAsArrayBuffer(file);

});

</script>

</body>

</html>



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。