以下是通过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>
本文转载自: https://blog.csdn.net/qq_44327851/article/details/135224127
版权归原作者 crary,记忆 所有, 如有侵权,请联系我们删除。
版权归原作者 crary,记忆 所有, 如有侵权,请联系我们删除。