input 標籤 type=「file「 隨筆

index.htmlcss

<!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{
                width: 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>

 

 

下面是獲取文件信息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);
    // }

    // })
}
相關文章
相關標籤/搜索