vue3中使用jszip压缩文件

28 篇文章 3 订阅

1、安装依赖

npm install jszip
npm install file-saver --save

2、使用

<template>
	<el-card class="mb15">
		<template #header>
			<span>jszip</span>
		</template>
        <!-- 二维码容器 -->
        <div id="qrCodeBox"></div>
    </el-card>
</template>

<script setup lang="ts" name="demoView">
import { ref, onMounted } from 'vue'
import QRCode from 'qrcodejs2-fix';
import html2canvas from 'html2canvas';
import JSZip from 'jszip'
import { saveAs } from 'file-saver';

const getQrCode = async () => {
    // 清空二维码容器内容
	document.getElementById('qrCodeBox').innerHTML = '';
	new QRCode(document.getElementById('qrCodeBox'), {
		//需要编码的文字内容或者URL
		text: '生成二维码',
		width: 200, //二维码宽
		height: 200, //二维码高
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
	});
    // 如果在dialog里展示二维码图片,则需要注意使用nextTick
};

const  base64img = ref()
const screenshot = async () => {
    html2canvas(document.querySelector('#qrCodeBox')).then(canvas => {
        base64img.value = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '')
        // 打压缩包
        tozip()
        // 如果打包多张截图,参考代码如下
        /*
            printImg(arr) {
                const base64Array = [];
                arr.forEach(item => {
                    let el = document.querySelector(`#zip${item.id}`)
                    html2canvas(el).then(canvas => {
                        base64Array.push({
                            name: `${item.id}.png`,
                            data: canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '')
                        });
                        if(base64Array.length == arr.length) {
                            this.downloadZip(base64Array,'二维码')
                        }
                    })
                })
            },
        */
    })
}

const tozip = () => {
    const zip = new JSZip();
    
    zip.file('1.png', base64img.value, { base64: true });
    zip.generateAsync({ type: 'blob' }).then(content => {
        saveAs(content, `压缩包.zip`)
    })
}

onMounted(async () => {
    // 生成二维码
    await getQrCode()
    // 截图
    await screenshot()
})
</script>

<style lang="scss" scoped>
#qrCodeBox {
    width: 200px;
    height: 200px;
}
</style>

3、页面

 4、效果

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值