Download attachments as ZIP

Last modified by Vincent Massol on 2026/06/02 17:54

cogDownload all attachments of a page as a ZIP file
TypeSnippet
CategoryOther
Developed by

Vincent Massol

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

Warning

Requires Programming Rights! An alternative is to export the page as HTML and unzip and find the attachments in the "attachment" folder.

{{groovy}}
import java.util.zip.*

def targetDoc = xwiki.getDocument('Sandbox.WebHome')
def attachments = targetDoc.getAttachmentList()

if (attachments.size() > 0) {
    // Check if the user clicked the download link
    if (request.confirm == '1') {
        def response = xcontext.getResponse()
        response.setContentType("application/zip")
        response.setHeader("Content-Disposition", "attachment; filename=\"${targetDoc.name}_attachments.zip\"")

        def out = response.getOutputStream()
        def zipStream = new ZipOutputStream(out)

        attachments.each { attach ->
            def entry = new ZipEntry(attach.filename)
            zipStream.putNextEntry(entry)
            // Stream the attachment content into the ZIP
            attach.getContentInputStream().withStream { is ->
                zipStream << is
            }
            zipStream.closeEntry()
        }

        zipStream.close()
        xcontext.setFinished(true)
    } else {
        println "((("
        println "This page has **${attachments.size()}** attachment(s)."
        println "[[Download All as ZIP>>||queryString='confirm=1']]"
        println ")))"
        
        attachments.each { println "* ${it.filename}" }
    }
} else {
    println "{{warning}}No attachments found on this page.{{/warning}}"
}
{{/groovy}}

Get Connected