Uploading images with MYSQL blob type
Let's say I have this model:
@Entity
public class Picture extends Model {
public Blob image;
...
}
When I look the type in mysql database it is just th开发者_StackOverflow中文版e path to the attachments folder (VARCHAR). Is there some way to change this to save the binary data into mysql (BLOB) using play?
I would like to achieve this:
CREATE TABLE picture (
......
image blob,
...
);
Using JDBC to set the image:
"psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length()));"
I don't know if this makes sense at all but if not please explain me why! Why having attachments folder into play project?
Well, because storing media files (images/videos/audio/etc etc) is very uncommon (in the database), I'm guessing the team placed that Blob implementation to make it more "effective" instead of fetching binaries in the database (the database will be less hammered). To be honest I never used the Blob function, I know you can just implement your own Blob and have read a few posts about it.
http://groups.google.com/group/play-framework/browse_thread/thread/7e7e0b00a48eeed9
Do note like Guillaume said, Blob is the new version of the "File Attachment" class that was used early before 1.1. If you want to store an image and you are using hibernate
@Entity
public class Picture extends Model {
@Lob(type = LobType.BLOB)
public byte[] image;
...
}
In Play the Blob type stores only the hash reference to the file plus its mime type. The reason is that databases don't like too much big Blobs (for internal reason) and it's a good practice to store the files aside. It will also avoid you headaches related to encodings and backups, trust me (and more importantly, trust Play developers!)
As an alternative, you can store your image as:
@Entity
public class YourClass extends Model {
@Basic(fetch = FetchType.LAZY)
@Lob
public byte[] image;
public String mime_type;
public String file_name;
}
You will need to store the mime type separately (Blob type stores it in the database in the field) to be able to work with the file, and you might want to store the original file name given to you. To detect the mime type I would recommend to use mime-util.
As a last note, be aware that if you use Play's Blob, when you delete the field (via CRUD or the API) the file is not removed from the file system. You will need to create a Job that checks for unused files from time to time, to free space.
This happens (in Gillaume's words) due to the impossibility of having a safe 2-phase transaction between the database and the file system. this is relevant, as depending on your application you might find your file system filled up by unused images :)
精彩评论