Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert binary data into sql server using node-mssql

I'm downloading an image using node/request module, and I'm trying to figure out how to insert that image into a varbinary field in sql server using the node/mssql module. So far I have tried putting a cast into the insert statement, converting the body (buffer) to a string, all to no avail. I'm trying to figure out how to do this without using a stored procedure.

Thanks!

like image 689
Danny Ackerman Avatar asked Jan 29 '26 17:01

Danny Ackerman


1 Answers

I've read in a .png image file from disk as 'binary', and then put that into a 'binary' buffer, and then was able to insert that into SQL Server DB using a prepared statement:

fs.readFile(<path-to-file>, 'binary', function(err, fileData) {
    var binBuff = new Buffer(fileData, 'binary');
    var ps = new sql.PreparedStatement(<connection>);
    ps.input('theImage', sql.VarBinary);
    ps.prepare('INSERT INTO ImageTable (BinaryImage) VALUES (@theImage)', function (err) {
        // check err
        ps.execute({theImage: binBuff}, function(err, records) {
            // check err
            ps.unprepare(function(err) {
                // check err
                // If no error, it's been inserted!
            });
        });
    });
});
like image 180
K Jackson Avatar answered Jan 31 '26 07:01

K Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!