Search code examples
sqlsql-servernode.jsmssql-jdbc

RequestError: Validation failed for parameter- Invalid buffer


Hi I have an error with mssql on node.js, I have to insert a string containing a file in base64 in a database sql server 2014, but when I insert the code below I have the following error:RequestError: Validation failed for parameter 'Immagine'. Invalid buffer. How Can I Solve it?

async function Reg(IdCantiere, IdUtenteCreazione, Data, Immagine) {

  var ret = true;

  await sql.connect(DbConfig.config);

  try {
    var request = new sql.Request();
    request.input('IdCantiere', sql.Int, IdCantiere);
    request.input('IdUtenteCreazione', sql.Int, IdUtenteCreazione);
    request.input('Immagine', sql.VarBinary(sql.MAX), Immagine);
    request.input('Data', sql.VarChar, Data);
    var query = "insert into Rapporto(IdCantiere,IdUtenteCreazione,NumeroDocumento,Data,Immagine) values(@IDCantiere,@IdUtenteCreazione,( /* Carico il l'ultimo numero  del rappportino di un utente*/ SELECT top 1 NumeroDocumento from Rapporto where Rapporto.IdUtenteCreazione=@IdUtenteCreazione and YEAR(Rapporto.Data)=YEAR(GETDATE()) order by CAST(Rapporto.NumeroDocumento  as int) desc),@Data,@Immagine); SELECT SCOPE_IDENTITY() as valore;";
    var recordset = await request.query(query);
    request = new sql.Request();
    request.input('IdRapporto', sql.Int, recordset.recordset[0].valore);
    recordset = await request.query('Insert into RapportoMobile(IdRapporto) values(@IdRapporto);');
  } catch (err) {
    ret = false;
    console.log("error -> ", err);
  }
  await sql.close();
  return ret;

}

Solution

  • I ran into the same issue when trying to put an encrypted value (stored as a string) into a VarBinary. Casting as a Buffer resolved the issue - new Buffer(someStringValue)

      const pool = await db.dbConnector();  //Setup mssql connection pool
      const result = await pool.request()
          .input('MerchantId', mssql.Int, merchantId)
          .input('AppKey', mssql.VarChar, applicationKey)  
          .input('AppSecret', mssql.VarBinary, new Buffer(encryptedApplicationSecret))
          .execute('[Security].[Account_Save]');
    

    Props to feiiiiii's comment for putting me on the right path