zoukankan      html  css  js  c++  java
  • 文件选择按钮随笔

    创建一个文件选择按钮:

    <input type="file" onchange="selectFiles(this)"/>

    也可以多选 加入 multiple="multiple"

    除IE以外均支持,网上解释为IE9及以下不支持

    方法:

    function selectFiles(self){
        console.log(self);
        console.log(self.files);
        console.log(self.value);

      console.log(self.files[0]);
    }

    self:按钮本身<input type="file" onchange="selectFiles(this)"/>

    self.files:按钮的files属性,一个FileList(文件列表,存在选取多个文件的情况)对象 FileList{}

    self.value:选取路径(绝对) eg:C:fakepathaa.png

    self.files[0]:选择的第一个文件,是一个file对象

    file对象主要属性:

    lastModified:最后被修改的时间

    lastModifiedDate:最后被修改的时间(世界时间)

    name: 文件名(不是路径)

    size:文件大小(字节) (数字类型)

    type: 类型 eg: "image/png"

    webkitRelativePath: 未知

    利用FileReader读取文件(注意大小写)

    首先检查浏览器是否支持FileReader

    注:主流除IE以外均良好支持,IE高版本部分支持

    详情:http://caniuse.mojijs.com/Home/Html/item/key/filereader/index.html

    因此最好加入兼容性判断

    if(typeof FileReader==='undefined'){
            console.log("不支持")
        }else{

       console.log("支持");

    });

    开始读取

        var preFile= self.files[0];
        console.log(preFile)
        if(preFile){      
            var reader = new FileReader();
            //文件编码为数据流
            reader.readAsDataURL(preFile);    
            reader.onload = function (event) {
                console.log(event)
                //获取数据流文件
                console.log(event.target)
                var bcdImg = event.target.result;
                console.log(bcdImg);
                var image = new Image()
                image.src = event.target.result;
                var width = image.naturalWidth;
                console.log(width);
            };     
        }

    解析:readAsDataURL()将文件解析为base64编码

    reader.onload 解析完毕

    event  progressevent对象(包含target属性)

    event.target.result 获取的base64数据流

    附加:判断文件是否为图片

    if(!/image/w+/.test(preFile.type)){
           alert("文件必须为图片!");
           return false;
    };

  • 相关阅读:
    setBackgroundResource和setImageResource的区别
    startActivityForResult 请求码不正确
    startActivityForResult 请求码不正确
    startActivityForResult 请求码不正确
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    android stadio svn 使用技巧
    android stadio svn 使用技巧
    android stadio svn 使用技巧
  • 原文地址:https://www.cnblogs.com/yanze/p/5973554.html
Copyright © 2011-2022 走看看