Grails下载文件

Mic*_*ael 7 grails file download

我使用这种方法将文件复制到我的项目中的文件夹(第一种方法),并且我已经编辑了它,因此位置存储在类提交中的"位置"上(见下文).

现在我希望能够在我的视图中单击图像后下载该文件.我怎样才能做到这一点 ?

class Submissions {

    Date dateSub
    String Location
    String fileName

}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 22

我做了类似以下的事情:

假设您的下载页面包含相关的提交实例...

<g:link action="downloadFile" id="${aSubmission.id}">
    <img>...etc...</img>
</g:link>
Run Code Online (Sandbox Code Playgroud)

然后在控制器(你的"位置"是文件的路径?):

def downloadFile = {
    def sub = Submissions.get(params.id)
    def file = new File("${sub.location}/${sub.fileName")
    if (file.exists())
    {
        response.setContentType("application/octet-stream") // or or image/JPEG or text/xml or whatever type the file is
        response.setHeader("Content-disposition", "attachment;filename=\"${file.name}\"")
        response.outputStream << file.bytes
    }
    else render "Error!" // appropriate error handling
}
Run Code Online (Sandbox Code Playgroud)


hvg*_*des 1

您只需要在响应上呈现字节即可。我们做类似的事情

def streamFile = {
    // load the attachment by id passed on params
    ....
    response.contentType = attachment.contentType.toLowerCase()
    response.contentLength = attachment.data.length()
    // our 'data' field is a Blob, the important thing here is to get the bytes according to
    // how you get the actual downlaod
    response.outputStream.write(attachment.data.getBytes(1L, attachment.data?.length() as int))
}
Run Code Online (Sandbox Code Playgroud)

在我们的控制器中,只需在 gsp 上创建指向该控制器方法的链接即可。根据您如何设置内容类型,浏览器将为您做一些事情。例如,如果您有图像类型,它将显示该图像。如果您有一个Word文档,浏览器应该打开适合用户系统的程序。