问题
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!
回答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!
});
});
});
});
来源:https://stackoverflow.com/questions/34383938/how-to-insert-binary-data-into-sql-server-using-node-mssql