如何在react.js中实现jszip [英] How to implement jszip in react.js
问题描述
我正在尝试通过http请求发送之前压缩文件列表.但是我被困在这里.
I am trying to zip a list of files before sending out through the http request. But I got stuck here.
export default function zipTargetFiles(files) {
if (files.length <= 1) {
return files;
} else {
const zip = require('jszip')();
for (let i = 0; i < files.length; i++) {
zip.file(files[i].name, files[i]);
}
return zip.generateAsync({type:"blob"});
}
}
基本上,该函数接收文件列表,然后尝试将它们压缩为一个单独的.zip文件.但是,当我将其作为格式数据发送出去时,出现了错误,即提交的数据不是文件.
Basically, the function takes in a list of files and tries to zip them into one single .zip file. But when i send it out as formed data, it gave the error that the submitted data was not a file.
我检查了标头中的有效负载,并且目标字段为[object Promise]
.如何真正返回.zip文件?
I checked the payload in the header and the target field is as [object Promise]
. How do I to truly return a .zip file?
现在,我可以在Redux-saga中捕获该zip文件,但是当我将其保存在数据库中时,它没有给出扩展名,而是仅将其命名为"blob".
Now I am able to catch the zip file in Redux-saga but it doesn't give an extension when I saved it in my database, instead it only give the name as 'blob'.
saga.js
const file = yield call(zipTargetFiles, files);
const formData = new FormData();
formData.append("coversheet", file);
const reponse = yield call(apiRequest, formData);
推荐答案
发生的事情是.generateAsync
正在返回承诺.您必须等到兑现诺言或兑现诺言之后,才能使用数据.
Whats happening is that .generateAsync
is returning a promise. You will have to wait until the promise is either fulfilled or rejected before being able to work with the data.
Promise是JS中使用异步操作时的核心概念.您可以在此处阅读有关承诺的更多信息
Promises is a core concept in JS when working with async operations. You can read more about promises here
import zipTargetFiles from '/path'
zipTargetFiles( data ).then(file => {
// Access your file here
})
这篇关于如何在react.js中实现jszip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!