JSZip下载压缩包,包含图片,表格等数据
要实现点击页面下载按钮,下载资源为本地压缩包功能,如图结果:
实现方式(React版本)
// index.tsx 页面文件
import React, { useRef } from "react";
import styles from "./index.less";
export default function DownloadZip() {
const contentRef = useRef<any>(null);
const csvData = [
{ name: "name1", age: 18 },
{ name: "name2", age: 20 },
{ name: "name3", age: 22 },
];
async function onClick() {
// 将页面dom元素转成图片 url
const imgUrl = await domToBlob(contentRef.current); // 引入下方工具函数domToBlob
const files = [
{
name: "csv数据表",
content: dataToCSV(csvData), // 引入下方工具函数dataToCSV
},
{
name: "随机图片.png",
content: imgUrl,
},
];
downloadZip(files, "下载.zip"); // 引入下方工具函数downloadZip
}
return (
<div className={styles.container}>
<button onClick={onClick}>DownloadZip</button>
<div ref={contentRef} className="download-image-content">
<h1>下载内容图片</h1>
<img src="https://picsum.photos/200/300" alt="" />
</div>
</div>
);
}
// index.less 样式文件
.container {
position: relative;
overflow: hidden;
:global {
.download-image-content {
position: absolute;
top: 0;
z-index: -1;
text-align: center;
}
}
}
// ts 工具文件
/**
* npm install jszip
*
* npm install papaparse
*
* npm install dom-to-image
*
*/
import JSZip from "jszip";
import Papa from "papaparse";
import domtoimage from "dom-to-image";
export type File = {
name: string;
content: any;
};
/** dom结构转blob */
export function domToBlob(
dom: any,
options?: {
width: 1200;
height: 1684;
}
) {
return domtoimage.toBlob(dom, options);
}
/** 数据转csv格式 */
export function dataToCSV(data: any[]) {
return Papa.unparse(data);
}
/** 下载blob */
export function downloadBlob(blob: any, filename: string) {
const blobUrl = URL.createObjectURL(blob); // 将blob对象转换成url地址
const a = document.createElement("a");
a.download = filename;
a.href = blobUrl;
a.click();
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
}, 1500);
}
/** 下载压缩包 */
export function downloadZip(files: File[], filename: string) {
var zip = new JSZip();
const promises: any = [];
files?.forEach((file) => {
promises.push(zip.file(file.name, file.content));
});
Promise.all(promises)
.then(() => {
zip.generateAsync({ type: "blob" }).then((blob) => {
downloadBlob(blob, filename);
});
})
.catch((error) => {
console.error("文件处理过程中发生错误", error);
});
}
原文地址:https://blog.csdn.net/zxo_apple/article/details/140522734
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!