3

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!

Danny Ackerman
  • 997
  • 1
  • 10
  • 25
  • Have you tried leaving it as a `Buffer`? The [docs for `node-mssql`](https://github.com/patriksimek/node-mssql#inputname-type-value) note that `Buffer` and `sql.VarBinary` are considered related. – Jonathan Lonowski Dec 20 '15 at 18:01
  • Can you please share the code you're using for the query? What is happening that indicates it "didn't work?" Are you receiving any errors? – Jonathan Lonowski Dec 20 '15 at 18:26

1 Answers1

1

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!
            });
        });
    });
});
K Jackson
  • 373
  • 1
  • 4
  • 13
  • Yes, works well for me. I can retrieve the image from the DB and renders just fine in a webpage. – K Jackson Mar 26 '17 at 21:53
  • thanks, it works, how about audio file? actually I tried to record audio binary file and want to play as remote url. – sirius2013 Mar 27 '17 at 06:36