gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:02:09 27 4
gpt4 key购买 nike

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

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

那没有帮助。但是有人告诉我Grails具有默认转换器。我在他们的图书馆里找不到任何东西。
有没有简单的方法可以将其转换为grails?

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

我的gsp View 表,这是用户看到的
<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的详细信息。

关于grails - 如何在Grails中转换字节文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29438247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com