如何从服务器下载文件,然后 post 在另一个服务器中再次下载 (Node.js)

How to download a file from a server, and and post it again in another one (Node.js)

在我的节点应用程序中,我想从一台服务器获取文件,然后将其上传到另一台服务器。我有以下代码:

const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");

const response = await axios({
  url: "https://first-server/image.png",
  method: "GET",
  responseType: "stream",
});

await new Promise((res) => {
  response.data.pipe(
    createWriteStream("someFile.png").on("finish", () => {
      res();
    })
  );
});

const form = new FormData();
form.append("file", createReadStream("./someFile.png"));

const postHeaders = {
  headers: {
    Authorization: "Bearer " + env("APY_KEY"),
    ...form.getHeaders(),
  },
  data: form,
};

axios.post("https://second-server.com/api", form, postHeaders)
  .then((response) => {
    console.log(JSON.stringify(response.data));
  })

此代码有效,但我认为这不是正确的方法,因为它会将检索到的文件写入本地磁盘,然后再将其重新发布到第二台服务器。我需要能够在不将文件写入本地光盘的情况下上传文件。有什么办法吗?

只需将 form.append("file", createReadStream("./someFile.png")); 替换为 form.append("file", response.data);

response.datacreateReadStream("./someFile.png")都是可读流。

注意:您可以直接传输返回的流数据,无需创建临时文件。

const axios = require("axios");
const FormData = require("form-data");

axios({
  url: "http://localhost:3000/temp.png",
  method: "GET",
  responseType: "stream",
}).then(response => {

    response.data.on("data", function(data) {
        const form = new FormData();
        form.append("file", data);

        const postHeaders = {
          headers: {
            // Authorization: "Bearer " + env("APY_KEY"),
            ...form.getHeaders(),
          },
          data: form,
        };

        axios.post("http://localhost:8000/api", form, postHeaders)
        .then((response) => {
            // console.log(JSON.stringify(response.data));
        })
        .catch(function(error){
            console.log(error)
        });
    });

})
.catch(function(error){
    console.log(error)
});