Reading a file from the local file system and saving it as binary data, using Grails

{ Posted on 6:49 PM by Alex P. }
I'm relatively new to Grails and recently ran into some difficulty when attempting to save a file, read in from the local file system, as a long-blob to MySQL. Most of the documentation I found dealt with saving of single files, uploaded by users of the website front-end. My situation was a little different. My application needed to accept jar file uploads through the front-end, requiring that I extract and recreate the entire jar's directory structure onto the server's local file system, before further processing and validation. The original data contained in these files would ultimately have to be saved to the database. One of these file types were java class files and needed to be stored into a MySQL database long_blob field as binary data.

Below is the way I created the domain class for these class files. I've omitted some fields for the sake of simplicity. Our class files' binary data will be stored into the 'byteCode' field. The code in the mapping closure is needed to make this work.

package org.netbeans.portals.admin

import java.sql.Blob;

class FileClass {
String fileName;
Blob byteCode;
Date createdAt = new Date();

static constraints = {
fileName(unique: true, nullable: false)
byteCode(nullable: false)
createdAt(nullable: false)
}

static mapping = {
columns {
byteCode type: "blob"
}
}
}


Below, is some simple code that returns a java.sql.Blob object, provided the path to a file, as a String. It converts the file into byte array, using the 'getBytesFromFile' method listed beneath it. using Hibernate's 'createBlob' method gives us the required sql blob which we can simple assign to our FileClass object's byteCode field.

    def getSqlBlobFromFile(String path) {
file = new File(path)
bytes = this.getBytesFromFile(file)
java.sql.Blob sqlBlob = null
if (bytes) {
sqlBlob = org.hibernate.Hibernate.createBlob(bytes)
}
return sqlBlob
}


***DISCLAIMER: I did not write the code, below.***
This is one of countless examples of converting a file to a byte array that can be found throughout the web. Unfortunately, I do not recall where I found it.

    private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
return null
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}


I hope this helps