首页 > 建站教程 > JS、jQ、TS >  原生js和vue实现input file选择图片本地预览正文

原生js和vue实现input file选择图片本地预览

原生js和Vue实现input file选择图片时,预览选择的图片的方法,用到了createObjectURL方法和readAsDataURL方法,前者是blob url,内存中的图片地址,后者是base64格式:

html的createObjectURL方法:
<input type="file" onchange="upload(event)" filetype="image/*"/>
<img src="" alt="" id="preview">
<script>
    function upload(event){
        var imgObj = event.target.files[0];
        var img=window.URL.createObjectURL(imgObj)
        document.getElementById("preview").setAttribute("src",img);
    };
</script>
html的new FileReader().readAsDataURL方法:
<input type="file" onchange="upload(event)" filetype="image/*"/>
<img src="" alt="" id="preview">
<script>
    function upload(event){
        var imgObj = event.target.files[0];
        const reader = new FileReader()
           reader.readAsDataURL(imgObj)
           reader.onloadend = function(r) {
            document.getElementById("preview").setAttribute("src",r.currentTarget.result);
        }
    };
</script>
vue的new FileReader().readAsDataURL方法:
<div id="rootVue">
    <input type="file" @change="upload($event)">
    <img :src="src">
</div>
<script>
new Vue({
    el:'#rootVue',
    data:{
        src:'',
    },
    methods:{
        upload:function(e){
            var that = this;
            var imgObj = e.target.files[0];
               const reader = new FileReader()
               reader.readAsDataURL(imgObj)
               reader.onloadend = function(r) {
                that.src = r.currentTarget.result;
            }
        }
    }
})
</script>
vue的createObjectURL方法:
<div id="rootVue">
    <input type="file" @change="upload($event)">
    <img :src="src">
</div>
<script>
new Vue({
    el:'#rootVue',
    data:{
        src:'',
    },
    methods:{
        upload:function(e){
            var that = this;
            var imgObj = e.target.files[0];
               var img=window.URL.createObjectURL(imgObj);
               this.src = img;
        }
    }
})
</script>