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{
                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>

 

 

下面是獲取文件信息

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);
    // }

    // })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM