簡體   English   中英

如何從 POST 請求中獲取帶有歸檔程序的壓縮文件?

[英]How can I get a compressed file with archiver from a POST request?

我正在使用 Express 構建一個NodeJS API ,當您進行POST ,它會根據請求正文生成一個TAR文件。

問題:

當端點是POST ,我可以訪問請求的正文,並且似乎可以用它來做事情。 但是,我無法從中看到/使用/測試壓縮文件(據我所知)。

當端點是GET ,我無權訪問請求的正文(據我所知),但我可以在瀏覽器中查詢 URL 並獲取壓縮文件。

基本上我想解決“據我所知”之一。 到目前為止,這是我的相關代碼:

const fs = require('fs');
const serverless = require('serverless-http');
const archiver = require('archiver');
const express = require('express');
const app = express();
const util = require('util');

app.use(express.json());


app.post('/', function(req, res) {
  var filename = 'export.tar';

  var output = fs.createWriteStream('/tmp/' + filename);

  output.on('close', function() {
    res.download('/tmp/' + filename, filename);
  });

  var archive = archiver('tar');

  archive.pipe(output);

  // This part does not work when this is a GET request.
  // The log works perfectly in a POST request, but I can't get the TAR file from the command line.
  res.req.body.files.forEach(file => {
    archive.append(file.content, { name: file.name });
    console.log(`Appending ${file.name} file: ${JSON.stringify(file, null, 2)}`);
  });

  // This part is dummy data that works with a GET request when I go to the URL in the browser
  archive.append(
    "<h1>Hello, World!</h1>",
    { name: 'index.html' }
  );

  archive.finalize();
});

我發送給這個的示例 JSON 正文數據:

{
  "title": "Sample Title",
  "files": [
    {
      "name": "index.html",
      "content": "<p>Hello, World!</p>"
    },
    {
      "name": "README.md",
      "content": "# Hello, World!"
    }
  ]
}

我只是應該發送JSON並獲得基於SON的 TAR 。 POST是錯誤的方法嗎? 如果我使用GET ,應該改變什么才能使用該JSON數據? 有沒有辦法“菊花鏈”請求(這看起來不干凈,但也許是解決方案)?

嘗試這個:

app.post('/', (req, res) => {
  const filename = 'export.tar';

  const archive = archiver('tar', {});

  archive.on('warning', (err) => {
    console.log(`WARN -> ${err}`);
  });

  archive.on('error', (err) => {
    console.log(`ERROR -> ${err}`);
  });

  const files = req.body.files || [];
  for (const file of files) {
    archive.append(file.content, { name: file.name });
    console.log(`Appending ${file.name} file: ${JSON.stringify(file, null, 2)}`);
  }

  try {
    if (files.length > 0) {
      archive.pipe(res);
      archive.finalize();
      return res.attachment(filename);
    } else {
      return res.send({ error: 'No files to be downloaded' });
    }
  } catch (e) {
    return res.send({ error: e.toString() });
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM