-
上傳圖片
- 本地預覽
- 獲取圖片大小
-
上傳視頻
-
本地預覽
-
獲取視頻
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);
參考: