如何在 Grails 中转换字节文件大小

How to convert a byte filesize in Grails

我正在上传文件并向用户显示文件名、文件日期和文件大小。

唯一的问题是当我显示文件大小时,它是以字节为单位显示的,所以一个 4 mb 的文件将是 4000000

这没有帮助。但是有人告诉我 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 这是用户看到的

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

您似乎正在尝试将字节值转换为兆字节。
例如 : 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的详细信息。