Search code examples
node.jsimage-processingnode-mssql

encoding and save images


I am a beginner with node.js and I would ask you for advice. Using a selection from the database I get the required data (ID, building, floor, map). The map is stored in jpg format as a byte array 0x89504E470D0A1A0A0000000D4948... . I save to a new database id, building, floor and reduced map (where quality is reduced through https://www.npmjs.com/package/images), which is now Unicode-encoded(http://puu.sh/g6UZ2/90408c7b12.png). Could you please advise me how to convert a reduced size map to a byte array and then store it in the database as a BLOB. Thank you and sorry for my English

var myQueryMaps2 = ' SELECT ' +
'id, budova, patro, mapa ' +
'FROM dbo.cis_mapyBudov';

app.get('/originalMaps', function (req, res) {

var request = new sql.Request(connection);
request.query(' DELETE FROM dbo.cis_mapyNewBudov', function (err) {
    if (err) {
        console.log(err);
    }
});
request.query(myQueryMaps2, function (err, rows, recordset) {
    if (!err && res.statusCode === 200) {
        for (var i = 0; i < rows.length; i++) {

            var insertSQL = "INSERT INTO dbo.cis_mapyNewBudov (id, budova, patro, mapa) VALUES ('" + rows[i].id +
                "', '" + rows[i].budova + "', '" + rows[i].patro + "', '" + images(rows[i].mapa).toBuffer('jpg', {quality: 50}) +
                "')";
            request.query(insertSQL, function (err) {
                if (err)
                    console.log(err);
                else
                    console.log('save');
            });
        }
    } else {
        console.log('error original maps', err);
        throw new Error('Can not download original maps');
    }
});

});


Solution

  • Use input parameters, it's almost always a bad idea to concatenate values into TSQL.

    var request = new sql.Request(connection);
    request.input('id', rows[i].id);
    request.input('budova', rows[i].budova);
    request.input('patro', rows[i].patro);
    request.input('mapa', sql.VarBinary(MAX), images(rows[i].mapa).toBuffer('jpg', {quality: 50}));
    request.query('INSERT INTO dbo.cis_mapyNewBudov (id, budova, patro, mapa) VALUES (@id, @budova, @patro, @mapa)', function (err) {
        // ...
    });
    

    Hint: Always create a new Request for each query. That's how the driver is designed. Reusing Request object might cause unexpected behavior.