input 标签 type=“file“ 随笔

index.html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <meta name="author" content="黄金亮">
        <title></title>
        <style>
            img{
                 100px;
            }
        </style>
        <!--<link href="index.css" rel="stylesheet">-->
    </head>
    <body>
        <!--上传文件时
        请求方法(method)因该设置为POST
        编码类型(enctype:encode type)应该设置为multipart-->
        <form action="#" method="POST" enctype="multipart/form-data">
            <!--accept表示期望的文件类型。格式:
            image/*
            .jpg,.png 或其他文件扩展名(后缀名)
            accept不是强制的,用户可以通过在弹出框上选择“所有文件”来选择任何文件
            添加multiple属性支持文件多选-->
            <input type="file" name="photo" accept=".jpg,.png" multiple>
        </form>
        <script src="index.js"></script>
    </body>
</html>

下面是获取文件信息

index.js

var input = document.querySelector("input")

input.onchange = function (event) {


        var file = input.files[0];
        var reader = new FileReader();
        // readAsText只能用来读取文本文件,不能用它读取图片等非文本文件
        reader.readAsText(file);

        reader.onload = function () {
            console.log(reader);
            
            // 通过result属性获得文本内容
            document.body.innerText = reader.result;
        }


    // console.log(event)
    // console.log(input.files)
    // 把一个类似数组的对象转换成数组方法:
    // ES5中老方法,几乎都支持 
    // console.log(Array.prototype.slice.call(input.files));
    // ES6中的新方法,注意手机浏览器支持不好
    // console.log(Array.from(input.files));
    // 使用Jquery或underscore等第三方脚本库中的方法
    
    // var files = Array.from(input.files);
    // files.forEach(function (file,index) {
    //     console.log(file.name);
    //     console.log((file.size/1024/1024).toFixed(3)+ "kb");

    // var url = URL.createObjectURL(file);
    // console.log(url);

    // console.log(file.type);

    // if (file.type.startsWith("image/")) {
    //     // console.log(file.type);
    //     var img = document.createElement("img");
    //     img.src = url;
    //     document.body.appendChild(img);

    //     // 通过img标签对象可以得到图片的原始宽度和高度,以及当前实际宽高
    //     console.log(img)

    //     // 实际上还是img标签元素,只是没有添加到页面上,通常用来做图片预加载
    //     var image = new Image();
    //     image.src = url;
    //     console.log(image);
    // }

    // })
}
原文地址:https://www.cnblogs.com/huangjinliang/p/5842147.html