【问题标题】:NodeJs send Binary Data with RequestNodeJs 通过请求发送二进制数据
【发布时间】:2019-01-04 19:25:28
【问题描述】:

我正在尝试使用 Wordpress rest API 将图像上传到 wordpress。

一切正常,但没有上传正确的图像。但是,当我使用卷曲图像时是正确的。

curl --request POST \
--url http://localhost/wordpress/wp-json/wp/v2/media/ \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=hh.jpg" \
--header "authorization: Basic token" \
--header "content-type: image/jpg" \
--data-binary "@C://Users/as/Desktop/App _Ideas/hh.jpg" \

此 curl 请求工作正常。

现在,当我将请求转换为 Nodejs 时

request({
        url: ' http://localhost/wordpress/wp-json/wp/v2/media/',
        headers: {
          'cache-control': 'no-cache',
          'content-disposition': 'attachment; filename='+filename,
          'content-type' : 'image/jpg',
          'authorization' : 'Basic token'
        },
        encoding: null,
        method: 'POST',
        body: "@C://Users/as/Desktop/App _Ideas/hh.jpg",
        encoding: null
       }, (error, response, body) => {
            if (error) {
               res.json({name : error});
            } else {
              res.json(JSON.parse(response.body.toString()));
            }
       });

当 imge 上传时,我能够从 wordpress 接收 json 响应。但是,上传的图像不正确,因为传递的二进制数据不正确。

Wordpress 上传文件夹显示文件hh.jpg 大小为 17 字节。使用记事本编辑时显示@hh.jpg,这意味着字符串数据保存为 hh.jpg 而不是实际的二进制数据。

关于如何使用 Nodejs 正确传递二进制数据的任何想法。

【问题讨论】:

  • 是的......你传递的身体是一个字符串。我猜@path 是 curl 的语法糖。
  • @alex-rokabilis 是的,你是对的。在使用记事本编辑上传的图像时,它显示 hh.jpg 表示由于 content-disposition 标头而将字符串另存为图像。
  • 知道如何正确上传吗?
  • 是的,试试body: require('fs').createReadStream("C://Users/as/Desktop/App _Ideas/hh.jpg")(我不确定windows中路径的正确格式,也许你需要反斜杠?)

标签: node.js


【解决方案1】:

搞定了,我们需要创建一个文件流

fs.createReadStream(filename);

fs 模块。

request({
        url: 'http://localhost/wordpress/wp-json/wp/v2/media/',
        method: 'POST',
        headers: {
          'cache-control': 'no-cache',
          'content-disposition': 'attachment; filename=' + filename,
          'content-type' : 'image/jpg',
          'authorization' : 'Basic token'
        },
        encoding: null,
        body: fs.createReadStream('C://Users/as/Desktop/App _Ideas/hh.jpg')
       }, (error, response, body) => {
            if (error) {
               res.json({name : error});
            } else {
              res.json(JSON.parse(response.body.toString()));
            }
       });

【讨论】:

  • 嗨。这对我不起作用。我应该使用 POST http 请求发送一个 tar 文件(二进制数据)。我可以用 Postman 做,但现在我做不到。我按照您的编码对其进行编码,有点尊重:headers: { 'Content-Type': 'application/x-tar' }body: fs.createReadStream(tarFilePath, { encoding: 'binary' }) 但它不会像邮递员那样发送文件。你能给我一点帮助吗?或使用 axios 更新您的答案。因为请求已弃用。
  • 你能告诉我如何下载这些文件吗?
  • 非常感谢兄弟。我几乎毁了我的笔记本电脑,因为我无法让它工作
猜你喜欢
  • 1970-01-01
  • 2019-11-24
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
相关资源
最近更新 更多