Search This Blog

Thursday, November 18, 2010

Grails: Storing Uploaded Files with Unique Names

This is how I was able to store uploaded files in a project directory rather than a blob in a database, as well as provide unique file names for each file by providing hash names.

Within my save action of the class with a property for the uploaded file

//handle uploaded file
def uploadedFile = request.getFile('file')
if(!uploadedFile.empty){
println "Class: ${uploadedFile.class}"
println "Name: ${uploadedFile.name}"
println "OriginalFileName: ${uploadedFile.originalFilename}"
println "Size: ${uploadedFile.size}"
println "ContentType: ${uploadedFile.contentType}"

//Creates hashed fileName using 128bit identifier
def splitName = uploadedFile.originalFilename.split("\\.") <--Splits the name of the file and the file type def hashedName = java.util.UUID.randomUUID().toString() def newFileName = hashedName + splitName[1].toString() //Sets the directory of the file
def dir = servletContext.getRealPath("/")
def userDir = new File(dir, "/uploaded/files")
userDir.mkdirs()
uploadedFile.transferTo( new File( userDir, newFileName))

No comments:

Post a Comment