【问题标题】:grails download this file as zipgrails 将此文件下载为 zip
【发布时间】:2014-11-07 08:32:38
【问题描述】:

我有这个功能代码,我只想下载它作为 zip 而不是它的原始文件 这是我的代码:

def downloadFile() {
    def filePath=ServletContextHolder.servletContext.getRealPath("/") + "Audio/"
    def sub = AudioClips.get(params.id)
    filePath+=sub.fileName
    def file = new File(filePath);
    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
        redirect(controller: "category",action: "index")
    }

【问题讨论】:

  • 你试过什么?您尝试过的方法有什么问题? SO 不是要求人们为您编写代码的地方。付出一些努力。下面是一个创建 zip 文件以帮助您入门的示例:groovy-almanac.org/create-a-zipfile

标签: grails grails-controller


【解决方案1】:
def downloadAudioZipFile = {
    def filePath = ServletContextHolder.servletContext.getRealPath("/") + "Audio/"
    def sub = AudioClips.get(params.id)
    filePath += sub.fileName
    def file = new File(filePath);
    if (file.exists()) {
        response.setContentType("application/octet-stream")

        response.setHeader("Content-Disposition", "Attachment;Filename=\"${file.name}\".zip")


        ZipOutputStream zip = new ZipOutputStream(response.outputStream);
        def file2Entry = new ZipEntry("${file.name}");
        zip.putNextEntry(file2Entry);
        zip.write(file.bytes)
        zip.close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多