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!

2
  • Have you tried leaving it as a Buffer? The docs for node-mssql note that Buffer and sql.VarBinary are considered related. Commented Dec 20, 2015 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? Commented Dec 20, 2015 at 18:26

1 Answer 1

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!
            });
        });
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, works well for me. I can retrieve the image from the DB and renders just fine in a webpage.
thanks, it works, how about audio file? actually I tried to record audio binary file and want to play as remote url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.