【问题标题】:HTTP POST raw binary data with Node.js and browser, without using form-data使用 Node.js 和浏览器的 HTTP POST 原始二进制数据,不使用表单数据
【发布时间】:2017-12-24 00:17:26
【问题描述】:

所以我可以把一张图片转成base64,然后用JSON POST图片数据,很方便,像这样:

    curl -u "username:pwd" \
    -X PUT \
    -H "Content-Type: application/json" \
    -d '{"image":"my-base64-str-data"}' \
    http://maven.nabisco.com/artifactory/cdt-repo/folder/unique-image-id

但是,我的问题是 - 有没有办法发送原始二进制图像数据而不是编码为 base64? cURL 或 Node.js 怎么能做到这一点?是否可以在 HTTP 请求中不使用表单数据来发送文件或二进制数据?

不过,归根结底,我想从浏览器发布图像,在这种情况下,将图像编码为 base64 可能是唯一的方法吗?

【问题讨论】:

标签: javascript node.js curl


【解决方案1】:

卷曲

正如您在curl manpage 上看到的,此表单的上传是通过指定数据字符串来完成的,并且可以直接从具有--data-binary @/path/to/file 语法的文件中完成:

  --data-binary <data>
          (HTTP) This posts data exactly as specified with no extra processing whatsoever.

          If you start the data with the letter @, the rest should be a filename.  Data is
          posted  in  a similar manner as --data-ascii does, except that newlines and car‐
          riage returns are preserved and conversions are never done.

          If this option is used several times, the ones following the first  will  append
          data as described in -d, --data.

如果图像仅在您的语言中以二进制字符串的形式提供,例如作为 Node.js 缓冲区,并且您不想访问文件系统,那么您可能必须通过将其包含在 @987654326 中来转义它@ 字符并将字符串中的每个' 字符替换为适当的转义序列,例如'\'',或者,如果这让您感到不安,则使用'"'"'。 (回想一下,echo 'abc'"def"'ghi' 会将 abcdefghi 回显为一个单元。)

Node.js

Node 更宽容一些,因为它有一个明确的缓冲区类型,但它确实需要更多的构造才能使其工作。在这里,我将返回数据包装在 Promise 中,以备不时之需:

const http = require("http");
function upload(image_buffer, image_id) {
  return new Promise((accept, reject) => {
    let options = {
      method: "PUT",
      hostname: "maven.nabisco.com",
      port: 80,
      path: "/artifactory/cdt-repo/folder/" + image_id,
      headers: {
        "Content-Type": "application/octet-stream",
        "Content-Length": image_buffer.length
      }
    };
    let data = [];
    let request = http.request(options, response => {
      response.on("data", chunk => data.push(chunk));
      response.on("end", () =>
        accept({
          headers: response.headers,
          statusCode: response.statusCode,
          data: Buffer.concat(data)
        })
      );
    });
    request.on("error", err => reject(err));

    request.write(image_buffer);
    request.end();
  });
}

【讨论】:

  • 太棒了,我会尝试的 - 知道如何在不使用表单数据的情况下将二进制数据从浏览器发送到服务器吗?这是我最大的问题 - 到目前为止,我只能使用带有 base64 字符串的表单数据,但我宁愿将图像作为原始二进制文件从浏览器发送到 Artifactory。
  • 是的,使用 --data-binary 有效 - 但就像我说的,我想找到一种方法将二进制数据从浏览器发送到服务器。
  • 谢谢,这就是我想出的(为浏览器使用更新的 Fetch API)-stackoverflow.com/questions/45179058/…
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 2018-02-05
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多