grails下载此文件为zip

时间:2014-11-07 08:32:38

标签: grails grails-controller

我有这个功能正常的代码,我只想将其下载为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")
    }

1 个答案:

答案 0 :(得分:0)

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();
    }
}