2015-04-03 34 views
0

我正在上传文件并向用户显示文件名,文件日期和文件大小。如何转换Grails中的字节文件大小

唯一的问题是,当我显示文件大小,它正在以字节为单位显示所以4 MB的文件将是400万

这是无益的。然而有人告诉我Grails有一个默认转换器。我看着他们的图书馆找不到任何东西。 有没有简单的方法在Grails中转换它?

这里是我的上传方法控制器:

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') 
} 

我GSP视图表,该表是用户看到

<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> 
+0

你的意思是像'org.apache.commons.io.FileUtils#byteCountToDisplaySize(fileSize)'? – cfrick 2015-04-03 19:47:55

+0

目前还不清楚你想要将4000000转换为。如果文件有4000000字节,你想显示什么? – 2015-04-03 19:50:03

+0

4 mb for examle @JeffScottBrown – Mozein 2015-04-03 19:51:05

回答

0

看来你正试图转换字节值转换成兆字节。
例如: 10485761 MB

对于这一点,你需要创建自定义标签库。为您的要求的taglib的简单的例子:

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

而且在GSP,

<g:convertToMB value="true"/> 

你可以看到custom tag library here细节。

相关问题