zoukankan      html  css  js  c++  java
  • 图片验证

    根据图片头信息验证

    
        const files = document.getElementById('files')
        const arr = [];
        files.onchange = async function(e) {
          const file = e.target.files;
          arr.push(file[0].slice(0, 6))
          const type = await blobToString(file[0].slice(0, 10))
          console.log(await isJpg(file[0]))
        }
    
        async function isGif(file) {
          // GIF89a 和 GIF87a
          // 前面6个16进制,'47 49 46 38 39 61' '47 49 46 38 37 61'
          const ret = await blobToString(file.slice(0, 6))
          return (ret === '47 49 46 38 39 61' || ret === '47 49 46 38 37 61')
        }
    
        async function isPng(file) {
          const ret = await blobToString(file.slice(0, 8))
          return ret === '89 50 4E 47 0D 0A 1A 0A'
        }
    
        async function isJpg(file) {
          const leng = file.size;
          const start = await blobToString(file.slice(0, 2))
          const end = await blobToString(file.slice(-2, leng))
          return (start === 'FF D8' && end === 'FF D9');
        }
    
        async function isImage(file) {
          // 通过文件流来判断,
          return await isGif(file) || await isPng(file)
        }
    
        function blobToString(blod) {
          return new Promise(resolve => {
            // 读取存储在用户计算机上的文件
            const reader = new FileReader();
            reader.onload = function() {
              const ret = reader.result.split('') // 转换为数组
                .map(v => v.charCodeAt()) // 转换 Unicode 编码 
                .map(v => v.toString(16).toUpperCase()) // 转换为 16进制 在将字符串转换为大写
                .map( v=> v.padStart(2, '0')) // 头部补全
                .join(' ');
              resolve(ret)
            }
            // 开始读取指定的Blob中的内容。一旦完成,result属性中将包含所读取文件的原始二进制数据。
            reader.readAsBinaryString(blod)
          })
        }
    
  • 相关阅读:
    网站备份list
    vnc checklist
    appnode iptables 规则后面覆盖前面的
    Appnode + Discuz checklist
    解决WORD文档无法显示链接的图像问题
    应用容器Application container
    要研究的内容
    转 Flex MXML编译成AS类
    Flex文件结构
    int a
  • 原文地址:https://www.cnblogs.com/wangyong1997/p/13992910.html
Copyright © 2011-2022 走看看