您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Vue读取文件名、文件大小和媒体时长

彭世瑜 发布时间:2020-11-21 23:29:13 ,浏览量:0



  
    

    
    

  



import { secondsToTime, byteToText, getObjectURL } from "./util.js";

export default {
  name: "app",

  data() {
    return {
      url: "",
    };
  },

  methods: {
    handleLoad(event) {
      let duration = event.target.duration;
      console.log(duration, secondsToTime(duration));
    },

    handleChange(event) {
      let file = event.target.files[0];

      console.log(file.name);
      console.log(file.size, byteToText(file.size));
      let url = getObjectURL(file);
      console.log(url);
      this.url = url;
    },
  },
};


用到的工具函数

// util.js

/**
 * 秒 转文本显示 x时y分z秒
 * @param {} secs
 */
export function secondsToTime(secs) {
  let hoursDiv = secs / 3600;
  // 向下取整
  let hours = Math.floor(hoursDiv);

  let minutesDiv = (secs % 3600) / 60;
  let minutes = Math.floor(minutesDiv);

  // 向上取整
  let seconds = Math.ceil((secs % 3600) % 60);

  if (seconds > 59) {
    seconds = 0;
    minutes = Math.ceil(minutesDiv);
  }

  if (minutes > 59) {
    minutes = 0;
    hours = Math.ceil(hoursDiv);
  }

  let timeStr = "";

  if (hours > 0) {
    timeStr += `${hours}时`;
  }
  if (minutes > 0) {
    timeStr += `${minutes}分`;
  }
  if (seconds > 0) {
    timeStr += `${seconds}秒`;
  }
  return timeStr;
}

/**
 * 字节大小转显示文本
 * @param {} size
 */
export function byteToText(size) {
  let mb = Math.floor(size / (1024 * 1024));
  let kb = Math.floor(size / 1024);

  if (mb > 0) {
    return (size / (1024 * 1024)).toFixed(2) + "MB";
  } else if (kb > 0) {
    return (size / 1024).toFixed(2) + "KB";
  } else {
    return size.toFixed(2) + "B";
  }
}

/**
 * 创建临时url
 * @param {*} file
 */
export function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) {
    // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) {
    // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

参考 怎样获得html5的audio组件加载的MP3文件的总时长

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.1236s