欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用vant上传图片功能(可多选)

程序员文章站 2022-03-22 10:05:01
上传图片
                    <div class="upimg">
                        <span>上传图片</span>
                        <van-uploader v-model="fileList" @delete="deleteimg" :after-read="afterRead" multiple
                            :max-count="9" />
                    </div>
<script>
    window.alert = function (name) {
        var iframe = document.createElement("IFRAME");
        iframe.style.display = "none";
        iframe.setAttribute("src", 'data:text/plain,');
        document.documentElement.appendChild(iframe);
        window.frames[0].window.alert(name);
        iframe.parentNode.removeChild(iframe);
    }
    new Vue({
        el: "#Vue",
        data: {
            fileList: [],
            imglist: []
        },
        created() {
            document.documentElement.style.fontSize = 16 * document.documentElement.clientWidth / 375 + 'px'
        },
        methods: {
            // 请求公共方法
            ajaximg(type, url, params, cb) {
                $.ajax({
                    type: type,
                    url: url,
                    data: params,
                    dataType: "json",
                    async: true,
                    contentType: false,
                    processData: false,
                    success: (response) => {
                        cb(response)
                    }
                });
            },
            afterRead(file) {
                // 此时可以自行将文件上传至服务器
                this.loadshow = true
                if (file.length > 1) {
                //使用for循环来适配多选情况
                    for (let i in file) {
                        this.upimg(file[i])
                    }
                } else {
                    this.upimg(file)
                }
            },
            //上传图片到服务器
            upimg(e) {
                var formData = new FormData();
                formData.append("file", e.file);
                formData.append("key", "Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO");
                formData.append("is_https", 1);
                this.ajaximg('post', 'https://ydnshop.hepulanerp.com/train/public/index.php/post/post/uploadFile', formData, (res) => {
                    let arry = this.imglist.concat(res.info.url) //前提是livehose是数组
                    this.imglist = arry
                    this.loadshow = false
                })
            },
            //删除图片
            deleteimg(file, detail) {
                this.imglist.splice(detail.index - 1, 1);
                console.log(this.imglist)
            },
        }
    })
</script>

本文地址:https://blog.csdn.net/hy3528/article/details/107311077