Class cast exception in Groovy

Class cast exception in Groovy

冷弦 发布于 2021-11-28 字数 1627 浏览 816 回复 3 原文

I want to upload an image using a groovy on grails.
My gsp page is as follows (I am showing a simplified version of the original)

<g:form controller="post" action="save" enctype="multipart/form-data">        
      My picture  <input type="file" name="myPicture" />     
    <g:submitButton name="submit" value="Save"/>

My domain class is as follows:

class Post {    

byte[] myPicture

static mapping = {
    myPicture type:  "blob" 

I need this mapping otherwise MySql will create a smallblob which is to small to fit the images

static constraints = {


At the controller I have an action called save which is as follows:

def save = {                               
    def post = loadPost( = params

    if( {
        print "hallo world"             
        redirect(action:'list', params:params)
    } else {
        render(view:'edit', model:[post:post])

The exception is thrown when I try to save the image at the DB.

2009-04-27 18:16:07,319 [20806951@qtp0-0] ERROR errors.GrailsExceptionResolver  - java.lang.ClassCastException: [B cannot be cast to java.sql.Blob

org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.ClassCastException: [B cannot be cast to java.sql.Blob

Any hint why is this?

BTW, I've seen in a tutorial that images were handled as strings but it didn't work
as well.

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


不即不离 2022-06-07 3 楼

try this way:

  def save = {                               

    def post = loadPost(

    def f = request.getFile('myPicture')             

    post.myPicture = f.getBytes()
    post.pictureType = f.getContentType()                    

    if( {
dawn曙光 2022-06-07 2 楼

Can you try using Spring's MultipartFile within your loadPost() method?

Here's an example from the docs:

def upload = {
    def f = request.getFile('myFile')
    if(!f.empty) {
      f.transferTo( new File('/some/local/dir/myfile.txt') )
    else {
       flash.message = 'file cannot be empty'

I believe you can access f.bytes directly.

新一帅帅 2022-06-07 1 楼

I found a similar question on Nabble:

Two possible solutions are suggested:

  • Change the constraints of the blob property to a large max-size, to stop it from using "TinyBlob".
  • Use the Hibernate Blob implementation instead of byte[] for the property's type declaration. This will require you stream data into the Blob, instead of direct assignment, but the post above gives code to do so.