在javascript中使用JSZIP提取压缩文件 [英] Extracting zipped files using JSZIP in javascript
问题描述
在我的网页中,用户应该上传压缩文件。在压缩文件中有2个文件:另一个zip文件和一个txt文件。在我的服务器上,收到zip后,我想解压缩zip文件以解压缩& txt文件,然后将这2个文件移动到预定义的文件夹。我有一段代码提取zip文件,但数据似乎不正确。首先,当只有1个txt文件时,它解压缩了一个zip和2个txt文件。它创建了一个额外的未定义txt文件。此外,在我的txt文件中,它替换为原始数据,而是替换为以下文本:'[undefined] [undefined]'。
有谁可以帮我这个?以下是我的代码:
In my webpage, a user is supposed to upload a zipped file. Within the zipped file are 2 files: another zip file and a txt file. On my server, after receiving the zip, I want to unzip the zip file to extract the zip & txt file, then move those 2 files to a predefined folder. I have a piece of code that extracts the zip file, but the data doesn't seem correct. Firstly, it unzipped a zip and 2 txt file when there should only be 1 txt file. It created an additional 'undefined' txt file. Also, in my txt file, instead of the original data, it was replaced with the following text: '[undefined] [undefined]'.
Can anyone help me on this? The following is my code:
var JSZip = require('JSZip');
fs.readFile( filePath, function(err, data){
if (!err){
var zip = new JSZip();
JSZip.loadAsync(data).then(function(zip){
object.keys(zip.files).forEach(function(filename){
var content = zip.files[filename];
var dest = path + filename;
fs.writeFileSync(dest, content);
});
});
}
});
推荐答案
他们的文档花了一些时间,但他们示例,展示如何从ZIP中读取文件内容。
It took a bit of digging in their documentation but they have an example that shows how to read the file contents from a ZIP.
您正在获取描述 ZIP内容但不是实际内容的对象。以下是调整后的版本:
You are getting the object that describes the ZIP contents but not the actual content. Here is an adjusted version:
var JSZip = require('JSZip');
fs.readFile(filePath, function(err, data) {
if (!err) {
var zip = new JSZip();
zip.loadAsync(data).then(function(contents) {
Object.keys(contents.files).forEach(function(filename) {
zip.file(filename).async('nodebuffer').then(function(content) {
var dest = path + filename;
fs.writeFileSync(dest, content);
});
});
});
}
});
这篇关于在javascript中使用JSZIP提取压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!