实现图片、音视频文件的上传预览

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title></title>
</head>

<script>
    function fileSelected(file, type) {
        var name = file.name;
        console.log(name);

        var path;
        if(type == "img") {
            if(document.all) // IE
            {
                // ele.select();
                path = document.selection.createRange().text;
                document.getElementById("temp").innerHTML = "";
                document.getElementById("temp").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" +
                    path + "\")"; // 使用滤镜效果
            } else // FF
            {
                path = URL.createObjectURL(file);
                document.getElementById("temp").src = path;
            }
        }
        if(type == "video") {
            path = URL.createObjectURL(file);
            // Todo:视频插件创建错误
            document.getElementById("video1").src = path;

            var myVideo = document.getElementById("video1");
            //音量为20%
            myVideo.volume = 0.2;
            /*myVideo.addEventListener("loadedmetadata", function() {
                initPlayUrl(myVideo.duration);
            }, false);
            myVideo.addEventListener("loadedmetadata", function() {
                drawVolumeSlider();
            }, false);
            return true;*/
        }
    }

    function choiceImg(e) {
        fileSelected(e.files[0], "img");
    }

    function choiceMusicAndVideo(e) {
        fileSelected(e.files[0], "video");
    }
</script>

<body>
<img src="img/123.jpg" id="temp" style="width: 300px;height: 417px;" />
<video width="400" height="300" id="video1" autoplay="autoplay" controls="controls" src="img/123.flv">

</video>
<input type="file" width="200px" onchange="choiceImg(this)" value="选择图片" />
<input type="file" width="200px" onchange="choiceMusicAndVideo(this)" value="选择音视频" />
</body>

</html>


说明:

当input的onchange事件触发的时候,获取选中的文件——this.files[0]
通过使用URL.createObjectURL(file)来生成一个临时的网络路径,最为上传文件的src。
发布者:songJian   点击数:1040   发布时间:2021-05-27 21:58:51   更新时间:2021-05-27 21:58:51
正在加载评论...
相关文章