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

雨燕双飞 提交于 2021-01-28 04:08:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!