Download all KB Attachments via Zip

Danielle Gallo
Kilo Expert

A knowledge base article in the Service Portal shows all attachments in a list and you can download them separately. I would like to add a Download Now button which lets you download all of the attachments at once via a zip file.

Has anyone done this?

3 REPLIES 3

Thiagofmeira
Kilo Guru
Hey Danielle, I believe this article solve your problem. https://servicenowguru.com/scripting/download-attachments-zip-file/

Community Alums
Not applicable

Hi @Danielle Gallo ,

You can use the same process as mentioned in this link. With slight modifications, you can get to download all attachments.

https://www.servicenowguru.com/scripting/download-attachments-zip-file/#comment-34336

Please note that the script might take time and if you want to limit to N number of records, you can do so in the below script. 

Few points to Note

1. The count variable is added to the file name to avoid duplicate file names. If there are duplicate file names, the zip process will break.

2. The script is modified to simply query sys_attachment and download them in the processor. It is not capturing any parameters from UI action as such. 

3. Create the UI action as a form button on any incident or any other table.

  var zipName = 'attachments.zip';
  var StringUtil = GlideStringUtil;
  var gr = new GlideRecord('sys_attachment');
  gr.query();
  if (gr.next()){
    g_response.setHeader('Pragma', 'public');
    g_response.addHeader('Cache-Control', 'max-age=0');
    g_response.setContentType('application/octet-stream');
    g_response.addHeader('Content-Disposition', 'attachment;filename=' + zipName);
    var out = new Packages.java.util.zip.ZipOutputStream(g_response.getOutputStream());
    var count=0;
    while (gr.next()){
        var sa = new GlideSysAttachment();
        var binData = sa.getBytes(gr); 
        //add counter so that the filename is NOT duplicate
        var file = gr.file_name+"-"+count; 
	gs.info("Entered into this loop"+file);
	addBytesToZip(out, zipName, file, binData);
        count ++;
    }
    // Complete the ZIP file
    out.close();
}

function addBytesToZip (out, dir, file, stream){
    // Add ZIP entry to output stream.
    out.putNextEntry(new Packages.java.util.zip.ZipEntry(file));
    out.write(stream, 0, stream.length);
    out.closeEntry();
}

 

Mark my answer correct & Helpful, if Applicable.

Thanks,

Sandeep

Hi @Community Alums ,

I tried creating the UI Action, but when clicking on the button, the following error occurred and no attachments got downloaded. Could you help me with troubleshooting it?

 

Aki18_0-1667805316909.png