Search code examples
node.jsoracle-databasenode-oracledb

Error trying to insert image to BLOB type in Oracle database using node-oracledb


Following this answer, I was trying to save a .jpg file to a BLOB type column inside a table. This is what I have so far:

I created a test table:

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

Then I wrote this code:

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);
      }
    }
  }
}

But I always get Error: ORA-01461: can bind a LONG value only for insert into a LONG column. What am I missing?


Solution

  • You read your image file as if it were a Unicode text string. That's not correct; you should read it as a buffer.

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

    I believe Oracle complains because you try to INSERT a Unicode string to a binary column. Try inserting the buffer.