I have a task to implement a download for files in excel format and images contained in a folder as a zip file. The API is a post but I use the JSzip library and I've not being able to get a proper implementation.
import { saveAs } from "file-saver";
import JSZip from "jszip";
function Download({ apiToken }) {
const [category, setCategory] = useState([]);
//click to download function
const handleClick = () => {
setButtonText("Downloading...");
const params = JSON.stringify({
subcategoryiid: category,
});
Axios({
url: `${baseUrl}/cards/details`,
method: "POST",
responseType: "blob",
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json",
"Content-Type": "application/json",
},
body: params,
})
.then((res) => {
console.log(res);
let zip = new JSZip();
let zipData = res.data;
zip.folder("project.zip", zipData);
zip.generateAsync({ type: "blob" }).then((content) => {
// Force down of the Zip file
saveAs(content, "project.zip");
});
})
.catch((err) => {
console.log(err);
setButtonText("Download");
});
};
return (
<div>
<TextField
className="box"
placeholder="enter facility code"
required
value={category}
onChange={(e) => setCatergory(e.target.value)}
/>
<Button
type="button"
color="success"
variant="contained"
onClick={handleClick}
>
{buttonText}
</Button>
</Paper>
</div>
);
}
export default Download;
I want to be able to read the file and download the folder(containing different files and images) as zip for the user to extract. The zip comes in empty whereas in the browser console it contains some files. I would appreciate any help please
This how I solve this case.
My Service
async download(appName: string): Promise<any> {
return fetch(`${this.URL}/download/${appName}`)
.then(transfer => transfer.blob())
.then(bytes => {
let elm = document.createElement('a');
elm.href = URL.createObjectURL(bytes);
elm.setAttribute('download', `${appName}.zip`);
elm.click()
return true;
})
.catch((error) => {
console.log(error);
})
}
How I call it
const onDownload = async () => {
setLoading(true);
const resp = await generateService.download(app.projectName);
if (resp) {
setLoading(false);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.