前端生成压缩文件demo

import { fromEvent } from 'rxjs';
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';

const file1 = 'https://yunpan-pub1.haixue.com/normal/2022/cms/c1aee512d90f4fd3850d6d01d28c4f25_1651044106084.png';
const file2 = 'https://imgstatic.highso.com.cn/2e36e0a2ea154b2fab95144954a006f8_1576467343167.png';

function urlToPromise(url) {
  return new Promise(function (resolve, reject) {
    JSZipUtils.getBinaryContent(url, function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

const button = document.createElement('button');
button.innerHTML = 'download';

document.body.appendChild(button);

fromEvent(button, 'click').subscribe({
  next() {
    const zip = new JSZip();
    zip.file('1.png', urlToPromise(file1), { binary: true });
    zip.file('2.png', urlToPromise(file2), { binary: true });
    zip.generateAsync({ type: 'blob' }).then(function callback(blob) {
      saveAs(blob, '压缩包.zip');
    }, console.error);
  },
});
 

你可能感兴趣的:(javascript,java,servlet)