make an HTTP request with an application/octet-stream content type - node js

15,280

Have you tried loading the file to a buffer rather than a stream? I appreciate in many contexts a stream is preferable, but often just loading into memory is acceptable. I've used this approach with no issues:

const imageBuffer = fs.readFileSync(fileName); // Set filename here..

const options = {
    uri: url, /* Set url here. */
    body: imageBuffer,
    headers: {
        'Content-Type': 'application/octet-stream'
    }
};


request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}

To do the same thing using a stream:

const options = {
    uri: url, /* Set url here. */
    body: fs.createReadStream(fileName),
    headers: {
        'Content-Type': 'application/octet-stream'
    }
};

request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
..
Share:
15,280

Related videos on Youtube

Ignas Poška
Author by

Ignas Poška

Updated on June 04, 2022

Comments

  • Ignas Poška
    Ignas Poška almost 2 years

    At the moment I am using npm module request to upload file with application/octet-stream content type. The problem is that I cannot get response body back. It is happening due to a known bug: https://github.com/request/request/issues/3108

    Can you provide me an alternate ways to upload file to an API with an application/octet-stream content type?

  • Ignas Poška
    Ignas Poška about 5 years
    Thank you, this solution works! Anyway, I think it is better to do it with streams, because videos are going to be uploaded using this program and size could be really big.
  • Terry Lennox
    Terry Lennox about 5 years
    If you're dealing with large files you should use streams alright!
  • Keven
    Keven over 4 years
    Can you provide an example how to do so the same thing with a stream?
  • Terry Lennox
    Terry Lennox over 4 years
    @Keven, I've updated with an example using a stream.