尝试使用 node-oracledb 在 Oracle 数据库中将图像插入到 BLOB 类型时出错

问题描述

this answer 之后,我尝试将 .jpg 文件保存到表内的 BLOB 类型列。这是我目前所拥有的:

我创建了一个测试表:

CREATE TABLE test_lob(
    ID NUMBER,C  CLOB,B  BLOB
);

然后我写了这段代码

async function getFile() {
  var str = fs.readFileSync('/path/to/image','utf8');
  await insertBlob(str);
}
...
async function insertBlob(str) {
  var connection;

  try {
    connection = await oracledb.getConnection({
      user:          process.env.USER,password:      process.env.PASS,connectString: process.env.SERVER_CONNECT_STRING
    });

    const result = await connection.execute(
      `
        INSERT INTO test_lob(id,b) VALUES(1,:b)
      `,{ b: str },{ autoCommit: true }
    );

    console.log(result);
  } catch(err) {
    console.error(err);
  } finally {
    if(connection) {
      try {
        await connection.close();
      } catch(err) {
        console.error(err);
      }
    }
  }
}

但我总是收到错误:ORA-01461:只能为插入到 LONG 列而绑定 LONG 值。我错过了什么?

解决方法

您将图像文件视为 Unicode 文本字符串。这是不对的;你应该把它当作一个缓冲区来读。

 var imageBuffer = fs.readFileSync('/path/to/image');
  await insertBlob(imageBuffer);

我相信 Oracle 会抱怨,因为您尝试将 Unicode 字符串插入到二进制列中。尝试插入缓冲区。