【问题标题】:Cloud Run - Attach compressed file to responseCloud Run - 将压缩文件附加到响应
【发布时间】:2021-03-17 03:28:40
【问题描述】:

我正在使用 Node 上的 functions-framework 包运行 Google Cloud Run 的测试环境。我目前正在尝试使用 .download 将 zip 文件附加到我的响应中,但我不相信该文件存在于测试云实例中,而它存在于我的文件中?抱歉,我真的不太了解正在发生的事情。

tldr:我正在尝试提示下载包含网站上所有图像的 zip,但我无法将 zip 附加到响应中

index.js

const puppeteer = require("puppeteer");
const archiver = require("archiver");
const fs = require("fs");

exports.screenshot = async (req, res) => {
  var output = fs.createWriteStream("./example.zip");
  var archive = archiver("zip");

  archive.on("error", function (err) {
    throw err;
  });

  archive.pipe(output);

  let browserPromise = puppeteer.launch({
    args: ["--no-sandbox"],
  });

  const url = req.query.url || "http://example.org";

  const browser = await browserPromise;
  const context = await browser.createIncognitoBrowserContext();
  const page = await context.newPage();

  await page.setViewport({ width: 3840, height: 2160 });
  await page.goto(url);

  const images = await page.evaluate(() =>
    Array.from(document.getElementsByTagName("img"), (e) => [
      e.x,
      e.y,
      e.width,
      e.height,
    ])
  );
 count = 0;
  await asyncForEach(images, async (image) => {
    count++;
    await page.evaluate(
      (y) => document.scrollingElement.scrollTo(0, y),
      image[1]
    );
    await page.screenshot({
      path: `image.png`,
      clip: {
        x: image[0],
        y: image[1],
        width: image[2],
        height: image[3],
      },
    });
    if (count < 10) {
      archive.file("./image.png", { name: `0${count}.png` });
    } else {
      archive.file("./image.png", { name: `${count}.png` });
    }
  });

  archive.finalize();
  //res.setHeader("Content-Type", "image/png");
  // res.set("Content-Type", "application/zip");
  // res.set("Content-Disposition", "attachment; filename=" + "example.zip");
  // res.download("/example.zip", "result.zip");
  // res.send("example.zip");

  context.close();
};

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

package.json

"scripts": {
    "start": "functions-framework --target=screenshot"
  },
"dependencies": {
    "@google-cloud/functions-framework": "^1.7.1",
    "archiver": "^5.1.0",
    "fs": "0.0.1-security",
    "puppeteer": "^5.5.0"
  }

【问题讨论】:

    标签: node.js asynchronous puppeteer google-cloud-run


    【解决方案1】:

    问题在于 Cloud Run 没有内置存储机制,文件只能临时存储在容器实例中进行处理,但这意味着您无法在要处理的应用程序旁边“部署”文件。

    对于持久存储,您必须将您的应用与 Cloud Storage 集成。

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 2021-05-24
      • 2021-10-18
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多