简体   繁体   中英

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.

Looking at examples for both the needle and request libraries, they all use form data examples. 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

Needle library 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.

// 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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