用html5的file api做一个简单的上传图片预览

html5的file api确实非常给力, 可以读到file选择文件的很多信息, 下面实现一个如何使用file api实现一个简单的上传图片预览

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>file</title>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
    <input type="file" id="file-upload" accept="image/*"/>
    <script>
    $("#file-upload").on("change", function(e){
        console.log(e);
        var file = this.files[0];
        console.log(this.files.length);
        var img = document.createElement("img");
        img.height="120";
        img.width="120";
        img.file = file;
        $("body").append(img);
        var reader = new FileReader();
        reader.onload = function(e){
            console.log(e);
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    });
    </script>
</body>
</html>

chrome 和 firefox最新版都通过

那么如何重置呢, 只需要将file元素的value等于""就OK了

posted on 2013-09-22 16:22  nobutawoproduce  阅读(370)  评论(0)    收藏  举报