node.js - Node JS 通过 HTTP 上传文件流

我正在将我的一个项目从 request 切换到更轻量级的项目(例如 got、axios 或 fetch)。一切进展顺利,但是,我在尝试上传文件流(PUTPOST)时遇到了问题。它适用于请求包,但其他三个中的任何一个都从服务器返回 500。

我知道 500 通常意味着服务器端有问题,但它只与我正在测试的 HTTP 包一致。当我恢复我的代码以使用 request 时,它工作正常。

这是我当前的请求代码:

Request.put(`http://endpoint.com`, {
  headers: {
    Authorization: `Bearer ${account.token.access_token}`
  },
  formData: {
    content: fs.createReadStream(localPath)
  }
}, (err, response, body) => {
  if (err) {
    return callback(err);
  }

  return callback(null, body);
});

这是使用另一个包的尝试之一(在本例中,得到):

got.put(`http://endpoint.com`, {
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${account.token.access_token}`,
  },
  body: {
    content: fs.createReadStream(localPath)
  }
})
  .then(response => {
    return callback(null, response.body);
  })
  .catch(err => {
    return callback(err);
  });

根据得到的文档,我也尝试根据它的示例将 form-data 包与它结合使用,但我仍然遇到同样的问题。

我可以收集到的这两个之间的唯一区别是 got 我必须手动指定 Content-Type header ,否则端点确实会给我一个正确的错误那。否则,我不确定这 2 个包是如何用流构造主体的,但正如我所说,fetchaxios 也产生与 得到

如果您想要使用 fetchaxios 的任何片段,我也很乐意发布它们。

最佳答案

我知道不久前有人问过这个问题,但我也错过了简单的 pipe support from the request package

const request = require('request');

request
  .get("https://res.cloudinary.com/demo/image/upload/sample.jpg")
  .pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))


// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
  .pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))

并且必须进行一些实验才能从当前库中找到类似的功能。

不幸的是,我还没有使用“got”,但我希望以下 2 个示例可以帮助其他对使用 Native http 感兴趣的人。/https图书馆或流行的 axios图书馆


HTTP/HTTPS

支持管道!

const http = require('http');
const https = require('https');

console.log("[i] Test pass-through: http/https");

// Note: http/https must match URL protocol
https.get(
  "https://res.cloudinary.com/demo/image/upload/sample.jpg",
  (imageStream) => {
    console.log("    [i] Received stream");

    imageStream.pipe(
      http.request("http://localhost:8000/api/upload/stream/", {
        method: "POST",
        headers: {
          "Content-Type": imageStream.headers["content-type"],
        },
      })
    );
  }
);

// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
  .pipe(
    http.request("http://localhost:8000/api/upload/stream/", {
      method: "POST",
      headers: {
        "Content-Type": imageStream.headers["content-type"],
      },
    })
  )

公理

注意 imageStream.data 的用法,它被附加到 Axios 配置中的 data

const axios = require('axios');

(async function selfInvokingFunction() {
  console.log("[i] Test pass-through: axios");

  const imageStream = await axios.get(
    "https://res.cloudinary.com/demo/image/upload/sample.jpg",
    {
      responseType: "stream", // Important to ensure axios provides stream
    }
  );

  console.log("  [i] Received stream");

  const upload = await axios({
    method: "post",
    url: "http://127.0.0.1:8000/api/upload/stream/",
    data: imageStream.data,
    headers: {
      "Content-Type": imageStream.headers["content-type"],
    },
  });

  console.log("Upload response", upload.data);
})();

https://stackoverflow.com/questions/38013111/

相关文章:

ruby - 符号有什么用?

android - 如何从 Android Studio 中的 Assets 中读取文本文件?

python - 找到坡度最陡的点 python

android - 完成其他 Activity 之前的所有 Activity

javascript - 如何使滚动条长度小于父 block ?

asp.net-mvc - 需要日期时间(+18 年)

intellij-idea - 为什么 IntelliJ IDEA 优先比较常量?

selenium - java.lang.NoClassDefFoundError : freema

r - 在 R 中组合两个具有不同行数的数据框

android - JSONObject.put(string,string) 不工作