Search code examples
grailsgsp

How to convert a byte filesize in Grails


I am uploading files and showing the file name, file date and file size to the user.

Only problem is when I show the filesize, it is being shown in bytes so a 4 mb file would be 4000000

That is not helpful. However someone told me that Grails has a default converter. I looked in their library could not find any. Is there a simple way to convert it in grails ?

Here is my upload method in the controller:

def upload() {
    def uploadedFile = request.getFile('file')
    if(uploadedFile.isEmpty())
    {
        flash.message = "File cannot be empty"
    }
    else
    {
        def documentInstance = new Document()
        documentInstance.filename = uploadedFile.originalFilename
        //fileSize
         documentInstance.fileSize = uploadedFile.size
        documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
        uploadedFile.transferTo(new File(documentInstance.fullPath))
        documentInstance.save()
    }
    redirect (action: 'list')
}

and my gsp view table which is what the user see

<table class="table-bordered" data-url="data1.json" data-height="299">
    <thead>
        <tr>
            <g:sortableColumn property="filename" title="Filename" />
            <g:sortableColumn property="fileSize" title="file Size" />
            <g:sortableColumn property="uploadDate" title="Upload Date" />
        </tr>
    </thead>
    <tbody>
    <g:each in="${documentInstanceList}" status="i" var="documentInstance">
        <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
            <td><g:link action="download" id="${documentInstance.id}">${documentInstance.filename}</g:link></td>
            <td><g:link id="${documentInstance.id}">${documentInstance.fileSize}></g:link></td>
            <td><g:formatDate date="${documentInstance.uploadDate}" /></td>
            <td><span class="button"><g:actionSubmit class="delete" controller="Document" action="delete" value="${message(code: 'default.button.delete.label', default: 'Delete')}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');" /></span></td>
        </tr>
    </g:each>
    </tbody>

Solution

  • It seems you are trying to convert bytes value into megabyte.
    For example : 1048576 to 1 MB

    For this, you need to create custom tag library. Simple example of taglib for your requirement :

    class FormatTagLib {
        def convertToMB = { attrs, body ->
            Integer bytes = attrs.value
            Float megabytes = bytes/(1024*1024)
            out << "${megabytes} MB"
        }
    }
    

    And in gsp,

    <g:convertToMB value="true"/>
    

    You can see details of custom tag library here.