开发的时候突然有个需求,就是我需要在vue里下载一个压缩包,但是压缩包里面有个文件里面有个参数XXXX需要根据我下载时候传的参数进行动态改变,查阅了资料找到了解决方法
需要安装 jszip
和 file-saver
这两个库
npm install jszip file-saver
然后编写代码
一.本地上传压缩包形式
<template>
<div>
<input type="file" @change="handleFileChange" accept=".zip" />
<button @click="processFile" :disabled="!file">处理文件</button>
</div>
</template>
<script setup lang="ts">
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import { ref } from 'vue';
const file = ref<File | null>(null);
const handleFileChange = (event: Event) => {
const target = event.target as HTMLInputElement;
if (target.files && target.files[0]) {
file.value = target.files[0];
}
};
const processFile = async () => {
if (!file.value) {
console.error('没有选择文件');
return;
}
try {
// 读取选中的文件
const zip = await JSZip.loadAsync(file.value);
// 获取 build.ts 文件
const myfile = zip.file('压缩包名字/你的文件');
if (myfile) {
const content = await myfile.async('text');
// 替换文件内容中的参数
const dynamicParameter = '你的参数'; // 替换为你实际的动态参数
const modifiedContent = content.replace('XXXXXXX(要替换的内容)', dynamicParameter);
// 将修改后的内容重新添加到压缩包
zip.file('压缩包名字/你的文件', modifiedContent);
// 生成新的压缩包并下载
const newZipBlob = await zip.generateAsync({ type: 'blob' });
saveAs(newZipBlob, 'modified-template.zip');
} else {
console.error('b文件未找到');
}
} catch (error) {
console.error('处理文件时发生错误', error);
}
};
</script>
二.服务器下载压缩包形式
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
/**
* 下载指定 URL 的压缩包,修改指定路径下的文件,并下载修改后的压缩包。
* @param replaceStr - 要替换到文件中的动态参数
*/
export const downloadAndProcess = async (replaceStr: string) => {
// 固定的压缩包 URL
const url = 'https://example.com/path/to/your/template.zip';
try {
// 下载压缩包
const response = await fetch(url);
if (!response.ok) {
console.warn('下载压缩包失败, 请检查网络!');
throw new Error('下载压缩包失败');
}
const blob = await response.blob();
// 读取压缩包
const zip = await JSZip.loadAsync(blob);
// 获取压缩包名下的文件
const buildTsFile = zip.file('压缩包名/文件名');
if (myFile) {
const content = await myFile.async('text');
// 替换文件内容中的参数
const dynamicParameter = replaceStr; // 替换为实际的动态参数
const modifiedContent = content.replace('XXXXX', dynamicParameter);
// 将修改后的内容重新添加到压缩包中
zip.file('压缩包名/文件名', modifiedContent);
// 生成新的压缩包并下载
const newZipBlob = await zip.generateAsync({ type: 'blob' });
saveAs(newZipBlob, 'myNewZip.zip');
} else {
console.error('文件未找到');
}
} catch (error) {
console.error('处理文件时发生错误', error);
}
};