vue after use readAsDataURL realized select a picture file preview

After vue realization select a picture file preview

It can be achieved using the api h5 select the file and preview

readAsDataURL

The method reads the specified Blob or File object. Read operation is complete when, readyState has been completed will become DONE, and trigger loadend event, while the result property will contain a data: string (base64 encoded) URL format to represent the contents of the file read

Introducing vue papers

<script src="./vue.js"></script>

File selection box, and add a change event, and operating ref dom

 <input type="file" @change="uploadImg" ref="img" />

Img add tags for displaying a preview

<img id="img" />

Examples of operations and complete vue

var vm = new Vue({
        el: '#app',
        methods: {
        //change事件
            uploadImg(el) {
                //根据ref得到图片文件
                var file = this.$refs.img;
                //使用h5的读取文件api
                var reader = new FileReader();
                reader.readAsDataURL(file.files[0]);
                //读取完成后触发
                reader.onload = function () {
                //改变img的路径
                    document.querySelector("img").src = this.result;
                };
            }
        },
    })

effect

file

The complete code

Cabin in the woods

More attention to my personal blog cabin in the woods

Guess you like

Origin www.cnblogs.com/mjsmry/p/11620946.html