-
上传图片
- 本地预览
- 获取图片大小
-
上传视频
-
本地预览
-
获取视频
duration
-
视频大小
-
图片上传
-
主要涉及内容
input
accept
filesList
URL.createObjectURL()
URL.revokeObjectURL()
-
input file
<label for='upload'></label> // ::before :: after 用于扩展可点击区域 <input type="file" id="upload" accept="image/*" onchange="upload(this.files)" > // 'video/*' 'audio/*' 'image/*'
获取
filsList
对象const selectedFile = document.getElementById('upload').files[0]; onchange="upload(this.files)" const inputElement = document.getElementById("upload"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { const fileList = this.files; // Filelist 对象 }
-
自定义上传框
- 隐藏
input
框 使用click
方法
<input type="file" id="upload" accept="image/*" style="display:none"> <button id="uploadBox">click to select files </button>
const inup = documnet.querySelector('#upload'); const inputBox = documnet.querySelector('#uploadBox'); inputBox.addEventListener("click", function (e) { if (input) { input.click(); } }, false);
label
<input type="file" id="upload" accept="image/*" class="visually-hidden"> <button id="uploadBox">click to select files </button>
// 不能使用 hidden display:none; 隐藏元素 // 使用定位 clicp || opcacity:0 ... .visually-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); }
::before
::after
// 不能使用 opacity hidden display:none // 使用定位 + overfollow:hidden .upload::before { content: ''; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background:whitesmoke; width: 100%; height: 100%; }
- 隐藏
-
使用
URL
对象实现本地预览const url = window.URL.createObjectURL(files[i]) let img = documnet.createElement('img'); img.src = url; img.height = 100; img.onload = function() { window.URL.revokeObjectURL(this.src); }
视频上传
获取 fileList
对象的方式、预览 跟上传图片一样 这里主要介绍一下获取视频 duration
<label for='upload'></label> // ::before :: after 用于扩展可点击区域
<input type="file" id="upload" accept="video/*" onchange="upload(this.files)" > // 'video/*' 'audio/*' 'image/*'
const input = document.querySelector('#upload');
function handleInput() {
const { files } = this;
const video = document.createElement('video');
// preload = 'metadata'
video.preload = 'metadata';
video.src = window.URL.createObjectURL(files[0]);
function loadMetaData(params) {
// 要实现本地预览则可以不用 revoke
window.URL.revokeObjectURL(video.src);
const { duration } = video;
console.log('😄 video duration ', duration);
}
// 监听 loadmetadata 事件
video.addEventListener('loadedmetadata', loadMetaData, false);
input.append(video);
}
input.addEventListener('change', handleInput, false);
参考: