【问题标题】:Create download link for static asset file为静态资产文件创建下载链接
【发布时间】:2018-04-25 11:31:31
【问题描述】:

我想在我的网站上放一个下载链接,以便用户可以下载文件template.csv。该文件是静态的,位于我的/grails-app/assets 文件夹的根目录下。

在我的page.gsp 中,我尝试了两种方法,但均无济于事:

  • <a href="assets/template.csv" download="template.csv">Download the template</a>
    • 这会导致下载一个template.csv 文件,但内容是page.gsp 的html 代码,而不是我在资产中上传的文件的原始内容。
  • <a href="${assetPath(src: "template.csv", absolute: true)}" download="template.csv">Download the template</a>
    • 生成的 html 文件有一个指向 localhost:8080/mysite/assets/template.csv 的链接,但单击它会提示错误消息:Failed - no file

什么是做我想要实现的正确方法?我需要添加额外权限以允许下载我的文件是否存在问题?

我们的 webapp 依赖于一个相当古老的技术栈:

  • Grails 2.3.4
  • 插件asset-pipeline-2.2.5

【问题讨论】:

  • 添加 grails 版本和有关您正在使用的任何资产处理插件的信息
  • @TuomasValtonen 我更新了我的问题

标签: html grails gsp


【解决方案1】:

我在使用 -tag 直接下载文件时遇到了一些麻烦。

为了克服这个问题,我使用Controller方法返回文件并将可下载的文件放在web-app/下自己的文件夹中:

class MyController {

    @Autowired()
    AssetResourceLocator assetResourceLocator

    def downloadExcelTemplate () {

        String fileName = "MyExcelFile.xlsx"

        /* Note: these files are found in /web-app/downloadable directory */

        Resource resource = assetResourceLocator.findResourceForURI("/downloadable/$fileName")

        response.setHeader "Content-disposition", "attachment; filename=${resource.filename}"
        response.contentType = 'application/vnd.ms-excel'
        response.outputStream << resource.inputStream.bytes
    }
}

并且只需使用常规的 a-tag 来链接到此控制器方法。 这样您还可以更好地控制文件下载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多