Create zip file with entries and download link

Here is an example on how to create a zip file for an attachment and sending a download link to the user.

First, the zip folder needs to be created. After that, file entries can be created inside the zip folder which hold the file information of the attachment by copying the attachment file information to the file entry.

The class “File” has a method called “SendFileToUser” which creates a download link of the zip file and sends the link to the user. The file is put into the temporary blob storage.

// Example of creating a zip file for a document attachment and sending a download link to the user.
public static void main(Args _args)
{
    System.IO.Stream fileStream;
    System.IO.MemoryStream zipArchiveStream = new System.IO.MemoryStream();
    DocuRef docuRef;
    DocuValue docuValue;

    const str extensionZip = '.zip';
    const str zipFileName = 'ZipDownload';
    
    select firstOnly docuRef
        join docuValue
        where docuValue.RecId == docuRef.ValueRecId;

    if (docuRef.RecId != 0)
    {
        // Creates the zip folder.
        using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(
            zipArchiveStream,
            System.IO.Compression.ZipArchiveMode::Create,
            true))
        {
            // Creates the file entry in the zip folder.
            System.IO.Compression.ZipArchiveEntry fileEntry = zipArchive.CreateEntry(docuValue.filename());
            
            // Opens the created file entry and copies the binary file information of the original file to the file entry in the zip folder.
            using (System.IO.Stream fileEntryStream = fileEntry.Open())
            {
                // Gets the file stream of the document attachment.
                fileStream = DocumentManagement::getAttachmentStream(docuRef);
                fileStream.CopyTo(fileEntryStream);
            }
        }

        // Send a download link of the created zip folder to the user. 
        File::SendFileToUser(zipArchiveStream, zipFileName + extensionZip);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s