无法上传照片Grails

时间:2013-06-21 04:04:25

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

我正在关注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)”

的值太长

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

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

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

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

请指教。谢谢!

3 个答案:

答案 0 :(得分:1)

在进行此avatar image uploader测试时,这对我不起作用。 我尝试了所有静态映射和其他答案无济于事。 <+ p>让我感到震惊的是什么

@Transactional(readOnly = true)

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

将临时failOnError:true放入保存方法是发现这些问题的快速技巧。即。domainObject.save(failOnError:true)

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

答案 1 :(得分:1)

您好我已经使用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)'
}

答案 2 :(得分:0)

您应该在约束中定义照片,如:

photo(nullable: true, maxSize: 32768))

最大尺寸为32k的照片。