简体   繁体   English

如何使用needle或请求库在Node.js中上传带有PUT请求的二进制主体

[英]How to upload a binary body with a PUT request in Node.js using needle or request libraries

I'm trying to write a unit test on an amazon pre-signed upload url which takes a PUT request with a raw binary body.我正在尝试在亚马逊预签名上传 url 上编写单元测试,该 url 接受带有原始二进制正文的 PUT 请求。

Looking at examples for both the needle and request libraries, they all use form data examples.查看needle 和request 库的示例,它们都使用表单数据示例。 Can someone give me an example using either library that will send a local file up as a raw binary in the body of the request?有人可以给我一个使用任何一个库的例子,它将本地文件作为原始二进制文件发送到请求正文中吗?

Request library https://github.com/request/request请求库https://github.com/request/request

Needle library https://github.com/tomas/needle针库https://github.com/tomas/needle

var filename = 'bunny.jpg';
var url = Amazon.getUploadUrl(filename);

var data = {
    file: __dirname + '/' + filename,
    content_type: 'image/jpeg'
};

var file = fs.createReadStream(__dirname + '/' + filename);
var request = require('needle');

request
    .put(url, data, function(err, resp) {

        console.log(resp.body.toString('utf-8'));
        if (resp.statusCode !== 200) {
            done(new Error(resp.statusMessage));

        }
        else
            done(err);
    });

I use promise-request to send binary body with a PUT request but you can adapt this code with request library or needle library.我使用promise-request发送带有 PUT 请求的二进制正文,但您可以使用请求库或针库修改此代码。

// Don't put encoding params in readFile function !
fs.readFile("example.torrent", function (err, file) {
    if (err) {
        throw err;
    }
    var r = request({
        method: 'PUT',
        uri: 'https://api.mywebsite.com/rest/1.0/addFile',
        headers: {
           "Content-Type": "application/octet-stream" // Because binary file
        },
        json: true // Because i want json response
    });
    r.body = file; // Put the file here
    r.then(function (response) {
        console.log("success", response);
    }).catch(function (error) {
        console.log("error", error);
    });
});

All you need to set is Content-Type header Using axios lib您需要设置的只是Content-Type标头 使用axios lib

return axios({
    method: "put",
    url: your_url,
    headers: { "Content-Type": "application/octet-stream" },
    data: Buffer.from(blob.data)
});

Where bolb is of type File (req.body.files)其中bolb的类型为 File (req.body.files)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM