Replies: 5 comments
This comment has been hidden.
This comment has been hidden.
-
大佬,按您的方法我设置了下,为何还是提示Uncaught (in promise) ReferenceError: jszip is not defined |
Beta Was this translation helpful? Give feedback.
-
大佬能帮忙看下的代码吗? |
Beta Was this translation helpful? Give feedback.
-
你好,我使用如下代码,能够打包后正常使用,并没有发现异常 // vite.config.ts
import { defineConfig } from 'vite';
import monkey, { cdn } from 'vite-plugin-monkey';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
monkey({
entry: 'src/main.ts',
userscript: {
icon: 'https://vitejs.dev/logo.svg',
namespace: 'npm/vite-plugin-monkey',
match: ['https://songe.li/'],
},
build: {
externalGlobals: {
jszip: cdn.jsdelivrFastly('JSZip', 'dist/jszip.min.js'),
},
},
}),
],
}); // main.ts
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
const zip = new JSZip();
zip.file('hello.txt', 'Hello World\n');
zip.file('hello2.txt', 'Hello World\n');
zip.file('test.bin', Uint8Array.from([0x00, 0x01, 0x02, 0x03]));
const content = await zip.generateAsync({ type: 'blob' });
saveAs(content, `test-${Date.now()}.zip`); |
Beta Was this translation helpful? Give feedback.
-
我用那个100#的直接复制粘贴,修改后,后来可以了,谢谢大佬! |
Beta Was this translation helpful? Give feedback.
-
大佬,我想把网页上的图片批量打包成zip后下载,在开发模式下,没有任何问题,但是打包后,却没法下载!
模块用了jszip和file-saver。
`const getFile = (url) => {
return new Promise((resolve, reject) => {
//通过请求获取文件blob格式
let xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET', url, true)
xmlhttp.responseType = 'blob'
xmlhttp.onload = function () {
if (this.status == 200) {
resolve(this.response)
} else {
reject(this.status)
}
}
xmlhttp.send()
})
}
const downFile = async (arrList) => {
// console.log(arrList)
const zip = new JSZip()
const cache = {}
const promises = []
await arrList.forEach((item) => {
const promise = getFile(item.src).then((data) => {
// 下载文件, 并存成ArrayBuffer对象
const lst = item.src.split('.')
const fileType = lst[lst.length - 1]
// console.log(fileType)
zip.file(Date.now() + '.' + fileType, data, { binary: true }) // 逐个添加文件
cache[item.fileName] = data
})
promises.push(promise)
})
Promise.all(promises).then(() => {
zip.generateAsync({ type: 'blob' }).then((content) => {
// 生成二进制流
// FileSaver.saveAs(content, '模板下载.zip') // 利用file-saver保存文件
// console.log(content)
downLoad(content, '模板下载','zip')
})
})
}
const downLoad = (blob, name, type) => {
if (!blob || !type) return
// const blob = new Blob([buffer], {
// type: 'application/arraybuffer',
// })
// 兼容不同浏览器的URL对象
const url = window.URL || window.webkitURL || window.moxURL
// 创建下载链接
const downloadHref = url.createObjectURL(blob)
// 创建a标签并为其添加属性
const link = document.createElement('a')
link.href = downloadHref
link.download =
${name || '导出文件'}.${type}
// 触发点击事件执行下载
document.body.appendChild(link)
link.click()
// 下载完成就删掉a标签
document.body.removeChild(link)
//释放blob对象
url.revokeObjectURL(downloadHref)
}`
上面改成a标签下载,还是不行,我自己看了下好像在zip.generateAsync这里的content一直打印不出来,有空帮忙看看啊!谢谢
Beta Was this translation helpful? Give feedback.
All reactions