简体   繁体   English

如何使用JSzip替换zip文件中的内容?

[英]How to replace contents of file in a zip using JSzip?

I have been working on a project, I download a zip file from internet through XMLHttpRequest (type: blob ) and then I try to read its content using JSzip.So every zip has a json which I am interested in say manifest.json. 我一直在从事一个项目,我通过XMLHttpRequest从Internet下载了一个zip文件(类型:blob),然后尝试使用JSzip读取其内容,因此每个zip都有一个我感兴趣的manifest.json文件。 So I was successful to read it with this code. 因此,我成功地用这段代码阅读了它。

var read_zip = new JSZip();
res=xhr.response;
read_zip.loadAsync(xhr.response).then(function (zip) {
return zip.file("manifest.json").async("string");
}).then(function (text) {
obj = JSON.parse(text);
console.log(text);});

after this I made some changes to 'obj', Now I want to replace the existing manifest with this modified 'obj' json contents and save it. 之后,我对'obj'进行了一些更改,现在我想用此修改后的'obj'json内容替换现有清单,并保存它。 I was trying this code 我正在尝试此代码

 var write_zip = new JSZip();
 write_zip.loadAsync(xhr.response).then(function (zip) {
 zip.file("manifest.json" , obj) ;
 zip.generateAsync({type:"blob"})
 .then(function (blob) {
 saveAs(blob, "hello.zip");
 });});

but I am getting this error 但我收到此错误

 Uncaught (in promise) Error: Can't read the data of 'manifest.json'. 
 Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) 
 ?

sorry, I am new to this. 抱歉,我是新来的。

It looks like you're trying to write an object into zip which is not supported. 似乎您正在尝试将对象写入zip,但不支持。 According to the documentation on JsZip the value to be written needs to be of type: 根据JsZip上的文档,要写入的值必须为以下类型:

String/ArrayBuffer/Uint8Array/Buffer/Blob/Promise/Nodejs stream String / ArrayBuffer / Uint8Array / Buffer / Blob / Promise / Nodejs流

See: JSZip#file(name, data [,options]) 请参阅: JSZip#file(名称,数据[,选项])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM