Search code examples
postgresqlscalaanorm

Insert image file in PostgreSQL using Anorm


I tried inserting the image into database but I am getting the error saying type mismatch; found : (Symbol, Array[Byte]) ; required: anorm.NamedParameter

Here is my code, anyone please help me out.

    def upload = Action(parse.multipartFormData) { request =>
    request.body.file("picture").map { picture =>
    import java.io.File
    val filename = picture.filename
    val contentType = picture.contentType
    println(filename)
    picture.ref.moveTo(new File("Image/rahul.jpg"))

    var fis = new FileInputStream("Image/rahul.jpg")

    var buf: Array[Byte]= new Array[Byte](fis.getChannel().size().toInt);
    fis.read(buf)
    var id = 341;
    DB.withConnection { implicit connection =>
   SQL(
      """
              INSERT INTO kyc(id,image)
              VALUES({id},{image})
      """).on(
        'id -> id,
        'image -> buf
      ).executeUpdate

Solution

  • As a workaround, tell play explicitly how to convert the Array[Byte]. Based on this posting I found that the following seems to work for me:

    implicit object byteArrayToStatement extends ToStatement[Array[Byte]] {
      def set(s: java.sql.PreparedStatement, i: Int, array: Array[Byte]): Unit = {
        s.setBlob(i, new javax.sql.rowset.serial.SerialBlob(array))
      }
    }
    implicit def rowToArray: Column[Array[Byte]] = Column.nonNull {
      (value, meta) =>
        value match {
          case byteArray: Array[Byte] => Right(byteArray)
          case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass))
        }
    }