Skip to main content

Download zip file returned from server in React

The app: I'm building an app that takes screenshots with puppeteer and returns them in a zip file to a react front end.

Relevant technologies: node, react, express, puppeteer, AdmZip

The issue: I can get the data to the point where it triggers the automatic download, but what gets downloaded does not appear to be a proper zip file as I get the following error when attempting to unzip: 'Unable to expand "screenshot-download.zip".

Extra context: To ensure things were working as expected in the process of actually compressing the screenshots into a zip file, I also implemented the "writeZip" method to create a zip file straight from the server and onto my local file system (bypassing converting to buffer and sending to client). This zip file worked as expected and had all the correct contents. This is leading me to believe that the issue is somewhere in the process of sending to client and converting it to something usable.

App.js code (front end):

fetch(`/dcsgrab?tearsheetUrl=${screenShotData}&imagefilelocation=${imageFileLocationData}`)
      .then((response) => response.json())
      .then((data) => {
        const zipBlob = new Blob(data.zipFile.data);
        const url = window.URL.createObjectURL(zipBlob);
        const zipDownload = document.createElement("a");

        setMessageData(data.message);
        setZipData(data.zipFile);

        zipDownload.href = url;
        zipDownload.download = "screenshot-download.zip";
        document.body.appendChild(zipDownload);
        zipDownload.click();
      });
  };

Console log values from returned data (top) and after it's converted to blob (bottom):

{message: 'Screenshots are done!\nPlease check the root directory you previously designated.', zipFile: {…}}
message: "Screenshots are done!\nPlease check the root directory you previously designated."
zipFile: {type: 'Buffer', data: Array(8207179)}
[[Prototype]]: Object

Blob {size: 21304601, type: ''}
size: 21304601
type: ""
[[Prototype]]: Blob

Server.js code (back end - large chunks of puppeteer code removed to make it easier to read through, if it seems necessary though I will add back in):

app.get('/dcsgrab', (request, response) => {
    const zip = new AdmZip();

    (async () => {

      /**
       * Screenshot the creative elements on the current page
       * @return {Promise.<Array>} Promise which resolves with an array of clipping paths
       */
        async function getScreenShots() {
            const rects = await page.$$eval(PREVIEW_SELECTOR, iframes => {
              return Array.from(iframes, (el) => {
                const {x, y, width, height} = el.getBoundingClientRect();

                return {
                  left: x,
                  top: y,
                  width,
                  height,
                  id: el.id,
                };
              });
            }, PREVIEW_SELECTOR).catch(e => {
              console.error(e.message);
            });

            return Promise.all(rects.map(async (rect) => {
              return await page.screenshot({
                clip: {
                  x: rect.left,
                  y: rect.top,
                  width: rect.width,
                  height: rect.height,
                },
              }).then((content) => {
                zip.addFile(`screenshot-${screenshotCounter++}.png`, Buffer.from(content, "utf8"), "entry comment goes here");
                console.log(`${rect.id} element captured and store in zip`);
              })
                .catch((e) => {
                  console.error(e.message);
                });
            }));
        }

        const zipToSend = zip.toBuffer();

        response.json({ 
            message: 'Screenshots are done!\nPlease check the root directory you previously designated.',
            zipFile: zipToSend
        });
    })();
}); 
Via Active questions tagged javascript - Stack Overflow https://ift.tt/RIXwFcQ

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data