input 文件上传实现本地预览

匿名 (未验证) 提交于 2019-12-02 23:49:02
  1. 上传图片
    • 本地预览
    • 获取图片大小
  2. 上传视频

    • 本地预览

    • 获取视频 duration
    • 视频大小

  1. 主要涉及内容

    • input accept
    • filesList
    • URL.createObjectURL()
    • URL.revokeObjectURL()
  2. 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 对象 }
  3. 自定义上传框
    • 隐藏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%; }
  4. 使用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/*'
 

参考:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!