0

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

请指教。谢谢!

4

3 回答 3

1

在进行此头像图片上传器测试时,这对我也不起作用。我尝试了所有静态映射和其他答案均无济于事。让我印象深刻的是

@Transactional(readOnly = true)

(自动生成的)控制器顶部的行。设置它来false解决问题。

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

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

于 2014-09-29T14:57:56.090 回答
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)'
}
于 2015-10-19T11:22:44.257 回答
0

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

photo(nullable: true, maxSize: 32768))

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

于 2013-06-21T04:12:54.093 回答