vue vant压缩图片 上传图片文件excel word

微信企业号参考 手机端图片较大 图片canvs上传压缩

企业微信手机端
代码片.

<template>
    <div>
        <van-nav-bar title="1"/>
        <h4 style="margin-top: 20px;text-align: center">1</h4>
        <van-uploader
                style="width: 100%"
                v-model="fileList"
                multiple
                max-count="10"
                :before-read="beforeRead"
                :max-size="5*1024*1024"
                @oversize="onOversize"
                @delete="delFile"
                :after-read="afterRead"
                accept=".jpg, .gif, .png, .jpeg, .txt, .pdf, .doc, .docx, .xls, .xlsx"
        />
        <div class="footer">
            <h6 style="margin-top: 10px;text-align: center">请垂直握紧手机,拍摄相关材料</h6>
            <!--<van-row class="foot-btn">
                      <van-button class="subBtn" type="primary" >
                          开始拍照
                      </van-button>
            </van-row>-->
            <van-row class="foot-btn">
                <van-button class="subBtn" @click="save">确定提交</van-button>
            </van-row>
            <van-row class="foot-btn">
                <van-button class="subBtn" type="primary" @click="onClickLeft">取消</van-button>
            </van-row>
        </div>
    </div>
</template>

<script>
    import {Toast} from "vant";

    export default {
        name: "bgswdj",
        data() {
            return {
                fileList: [],
                picList: [],
                canUpSave: 0,
                matterToDoForm: {
                    tdDm: "",
                    nsrsbh: "",
                    picList: "",
                    yhId: sessionStorage.getItem("userId"),
                    value: "",
                },
            };
        },
        mounted() {
            this.matterToDoForm.nsrsbh = this.$route.query.nsrsbh;
            this.matterToDoForm.tdDm = this.$route.query.tdDm;
        },
        methods: {
            onClickLeft() {
                this.$router.push("/");
            },
            afterRead(files) {
                const formData = new FormData();
                if (files instanceof Array && files.length) {
                    // 判断是否是多图上传 多图则循环添加进去
                    files.forEach((item) => {
                        console.log(item.file.size);
                        this.compressImage(item);
                        //   formData.append("files", item.file); //第一个参数字符串可以填任意命名,第二个根据对象属性来找到file
                    });
                } else {
                    console.log("压缩前");
                    console.log(files.file.size);
                    this.compressImage(files);
                    // formData.append("files", files.file);
                }
                //   this.$http.post("/oss/file/uploadList", formData).then((r) => {
                //     if (r.data) {
                //       r.data.forEach((item) => {
                //         this.picList.push(item.url);
                //       });
                //     } else {
                //       Toast.fail("上传失败!");
                //       this.fileList = [];
                //     }
                //   });
            },
            save() {
                if (this.canUpSave === 0) {
                    Notify({
                        type: "warning",
                        duration: 1500,
                        message: "请等待图片上传完成",
                    });
                    return;
                }
                if (this.picList.length === 0) {
                    Toast("请先选择图片");
                    return;
                }
                this.matterToDoForm.picList = this.picList.join(";");
                let data = {
                    tdDm: this.matterToDoForm.tdDm,
                    nsrsbh: this.matterToDoForm.nsrsbh,
                    yhId: this.matterToDoForm.yhId,
                    bgxxfyj: this.matterToDoForm.picList,
                };
                this.matterToDoForm.value = JSON.stringify(data);
                console.log(this.matterToDoForm);
                this.$http
                    .post(`/api/matterToDo/save/`, this.matterToDoForm)
                    .then((data) => {
                        console.log(data.data);
                        if (data.data) {
                            Toast.success("办理成功!");
                            this.$router.push({path: "/index"});
                        } else {
                            Toast.fail("办理失败!");
                            this.fileList = [];
                        }
                    });
            },
            beforeRead(files) {
                if (files.length > 10) {
                    Toast("最多只能上传十张图片");
                    return false;
                }
                return true;
            },
            onOversize(file) {
                if (file.file.size() > 5 * 1024 * 1024) {
                    Toast("文件大小不能超过 5M");
                    return;
                }
            },
            delFile(file, index) {
                this.picList.splice(index, 1);
            },
            compressImage(file) {
                file.status = "uploading";
                file.message = "上传中...";
                // 大于1MB的jpeg和png图片都缩小像素上传
                if (
                    /\/(?:jpeg|png|jpg|bmp)/i.test(file.file.type) &&
                    file.file.size > 1000000
                ) {
                    const canvas = document.createElement("canvas"); // 创建Canvas对象(画布)
                    const context = canvas.getContext("2d");
                    const img = new Image();
                    img.src = file.content; // 指定图片的DataURL(图片的base64编码数据)
                    img.onload = () => {
                        canvas.width = img.width;
                        canvas.height = img.height;
                        context.drawImage(img, 0, 0, img.width, img.height);
                        file.content = canvas.toDataURL(file.file.type, 0.8); // 0.92为默认压缩质量
                        const files = this.dataURLtoFile(file.content, file.file.name);
                        // let lastfile = this.dataURLtoFile(file.content);
                        let uploadImg = this.upLoaderImg(files);
                    };
                } else {
                    let uploadImg = this.upLoaderImg(file.file);
                }
                setTimeout(() => {
                    file.status = 'done';
                    file.message = '';
                }, 1000);
            },
            dataURLtoFile(dataurl, filename) {
                // 将base64转换为file文件
                const arr = dataurl.split(",");
                const mime = arr[0].match(/:(.*?);/)[1];
                const bstr = atob(arr[1]);
                let n = bstr.length;
                const u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {type: mime});
            },

            //把file转换成二进制形式(binart)
            upLoaderImg(file) {
                console.log("压缩后");
                //file为 你读取成功的回调文件信息
                console.log(file.type);
                console.log(file.size);
                //new 一个FormData格式的参数
                let params = new FormData();
                // let url = Urls.upload_image;
                params.append("files", file);
                this.$http.post("/oss/file/uploadList", params).then((r) => {
                    if (r.data) {
                        r.data.forEach((item) => {
                            this.picList.push(item.url);
                        });
                        this.canUpSave = 1;
                    } else {
                        Toast.fail("上传失败!");
                        this.fileList = [];
                    }
                });
            },
        },
    };
</script>

<style scoped>
    body {
        background: rgba(245, 245, 245, 1) !important;
    }

    .subBtn {
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
        width: calc(100% - 32px);
        height: 47px;
        background: rgba(83, 131, 236, 1);
        border-radius: 4px;
        text-align: center;
        line-height: 47px;
        margin: auto;
    }

    .footer {
        height: 160px;
    }

    .foot-btn {
        margin-top: 10px;
        margin-left: 20px;
    }
</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值