2

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);
    });
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

2 Answers2

2

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);
    });
});
Piitaya
  • 21
  • 2
0

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)

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189