Handling binary image or files with NodeJS/ExpressJS through POST request

Viewed 727

I would like to know if there is a way to handle a POST request containing just a file, no form, just a binary sent as body of the request.

const path = require('path');
const express = require('express');
const app = express();
const logger = require('morgan');

// Settings
app.set('port', process.env.PORT || 3000)

// Middlewares
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.post('/upload', (req, res) => {
    console.log(req.headers);
    
    let data = ''
    
    req.on('data', chunk => {
        data += chunk;
    })

    req.on('end', () => {
        fs.writeFileSync('img.jpg', data)
    })
    
    res.send('ok');
})

app.listen(app.get('port'), console.log(`Listening on any ${app.get('port')}`));

I've tried to make this request: (sorry for external link, I just created the account)

POSTMAN, using binary option

Headers:

{
  'user-agent': 'PostmanRuntime/7.26.5',
  accept: '*/*',
  'postman-token': 'aca04fab-a66d-439a-962f-87ede2b8bb98', 
  host: 'localhost:3000',
  connection: 'keep-alive',
  'content-length': '73989'
}

and is not working, img.jpg is just corrupt.

UPDATE: (thanks to eol for his help)

This is how code works now, with express.raw built-in middleware:

app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.raw({type: '*/*'}));

app.post('/upload', (req, res) => {
    fs.writeFileSync('img.jpg', req.body);
    res.send('ok');
})
1 Answers

The built-in bodyparser should be able to do this out of the box as far as I know. Try setting it up with:

app.use(express.raw({type: 'application/octet-stream'}))

Inside your handler req.body should then hold a buffer of the content:

app.post('/upload', (req, res) => {
  // req.body should hold the bindary-data as a buffer
});
Related