【问题标题】:Trouble uploading photo Grails无法上传照片 Grails
【发布时间】:2013-06-21 04:04:25
【问题描述】:

我正在关注 Book Grails In Action。第 5.5 节是如何将照片上传到用户资料的示例。没什么复杂的:

class Profile {
static belongsTo = User

byte[] photo
String fullName
String bio
String homepage
String email
String timezone
String country
String jabberAddress

String toString() {
    "Perfil para ${fullName} (${id})"
}

static constraints = {
    fullName(nullable: true)
    bio(nullable: true, maxSize: 1000)
    homepage(nullable: true, url: true)
    email(nullable: true, email: true)
    photo(nullable: true)
    country(nullable:true)
    timezone(nullable: true)
    jabberAddress(nullable: true, email: true)
}   

}

使用源代码中的 Profile 和 ImageController 代码,尝试上传照片(大小小于 10kb)时出现此错误:

“PHOTO BINARY(255)”列的值太长

我尝试了各种方法来更改列定义以接受更大的字节[],包括:

1) 在 Profile 约束中,设置 maxSize: 1024*200 2)在Profile mappings中,设置照片类型:“byte[]”,长度:1024*200

在映射中,我尝试了 type|sqlType:byte|byte[]|blob|binary 的各种组合,但是值太长(对于 byte[])或对于其他类型(例如,blob):

[B 不能转换为 java.sql.Blob

请指教。谢谢!

【问题讨论】:

  • 你在使用 photoUploadCommand 吗?如果是,您是否在那里设置了约束?
  • 你用的是什么数据库?

标签: grails grails-orm grails-2.0 grails-domain-class grails-controller


【解决方案1】:

在进行 avatar image uploader 测试时,这对我也不起作用。 我尝试了所有静态映射和其他答案均无济于事。让我印象深刻的是

@Transactional(readOnly = true)

(自动生成的)控制器顶部的行。将其设置为false 解决了这个问题。

在 save 方法中加入一个临时的failOnError:true 是发现这些问题的快速技巧。即domainObject.save(failOnError:true)

我通常会使用具有写入权限的服务来保存此图像。

【讨论】:

    【解决方案2】:

    您好,我已经使用 oracle 和 h2 数据库完成了这项工作。它对我有用...

    域名喜欢

    package com.so
    
    class Profile {
    
    String firstName
    String lastName
    String skillSet
    
    byte[] profilePhoto
    
    static belongsTo = [user:User]
    
    static constraints = {
        firstName(blank:false)
        lastName(blank:false)
        skillSet(blank:false)
        profilePhoto(nullable:true) 
    }
    
    static mapping = {
        profilePhoto sqlType:'blob'
    }
    

    }

    还有控制器……

     def uploadProfilePhoto(){
        def file = new File(/C:\Users\Public\Pictures\Sample Pictures\Desert.jpg/)
        def profile = Profile.get(1)
        profile.profilePhoto = file.bytes
        profile.save()
        redirect action:'showProfilePhoto'
    }
    

    希望这会有所帮助。

    也适用于 MsSQL

     static mapping = {
        profilePhoto sqlType:'VARBINARY(max)'
    }
    

    【讨论】:

      【解决方案3】:

      您应该在以下约束中定义照片:

      photo(nullable: true, maxSize: 32768))
      

      对于最大尺寸为 32k 的照片。

      【讨论】:

      • 我跟着同一本书,如果您尝试使用非常小的图像(小于 32k)怎么办?
      • 我尝试了各种组合和非常小的图像(小于 5KB)。我添加静态映射 = {照片列:“照片”,sqlType:“blob”}。没有。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2012-03-12
      • 2011-01-03
      相关资源
      最近更新 更多