Reputation: 672
I'm following the Book Grails In Action. Section 5.5 is an example of how to upload a photo to a user profile. Nothing complicated:
Domain
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)
}
}
Using the Profile and ImageController code in the source, I get this error trying to upload a photo (size less than 10kb):
Value too long for column "PHOTO BINARY(255)"
I have tried various methods to alter the column definition to accept a larger byte[], including:
1) in Profile constraints, setting maxSize: 1024*200 2) in Profile mappings, setting photo type:"byte[]", length:1024*200
in the mappings I have tried various combinations of type|sqlType:byte|byte[]|blob|binary but either the value is too long (for byte[]) or for the other types (eg, blob):
[B cannot be cast to java.sql.Blob
Please advise. Thanks!
Upvotes: 0
Views: 1678
Reputation: 697
Hello I have done this with oracle and h2 database. It worked for me...
Domain like
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'
}
}
and controller like...
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'
}
Hope this helps.
And also for MsSQL
static mapping = {
profilePhoto sqlType:'VARBINARY(max)'
}
Upvotes: 1
Reputation: 5767
This wasn't working for me either while doing this avatar image uploader test. I tried all the static mapping and other answers to no avail. What caught me out was the
@Transactional(readOnly = true)
line at the top of the (auto generated) Controller. Setting it to false
fixed the problem.
Putting in a temporary failOnError:true
into the save method is a quick trick for spotting these problems. i.e.domainObject.save(failOnError:true)
I'd normally have used a Service with write access to save this image.
Upvotes: 1
Reputation: 6075
You should define photo in the constraints like:
photo(nullable: true, maxSize: 32768))
for a photo of maximum size of 32k.
Upvotes: 0