Javascript 创建 zip 文件

Javascript create zip file

我正在使用 react.js 和 admin-on-rest 开发一个网站。其中一项功能是允许用户上传 pdf 文件。

我获取类型为 FILE 的文件,并希望从 FILE 获取文件,将其压缩为 zip,然后使其类型为 FILE.

所以它应该是 FILE -> 原始文件 -> zip 文件 -> FILE 来自 zip 文件。

我尝试了 JSZip,但仍然无法理解。

感谢任何帮助。谢谢

为此有一个名为 jszip 的小应用程序。试试吧,会有帮助的。 https://stuk.github.io/jszip/

您好 Garrick 以下是您需要执行的步骤。

1) 在 rest 包装器中处理文件上传 https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

以上示例是图片上传。但你基本上会做同样的事情。

2)

const addUploadCapabilities = requestHandler => (type, resource, params) => {
    if (type === 'UPDATE' && resource === 'posts') {
       //use jszip to zip file here and package it however you need
       // call the API with zipped file
   } return requestHandler(type, resource, params);
};

您可以使用 JSZIP.

**使用 npm 安装 JSZIP

let zip = require('jszip')();
//hoping you have already taken input
let input = document.getElementById('fileInput'); // fileInput is id of my input element
let file = input.files[0];
let allZip =  zip.file(file.name, file);
console.log(allZip)