Thursday 4 May 2023

Download multiple files as Zip from blob using x++ code

 Download file from blob

    public static System.IO.Stream   downloadFromBlob(ENCDocumentType _documentType, Filename _fileName)

    {

        Filename folder = ENCBlobUtil::getBlobFolderName(_documentType);

        try

        {

            CloudStorageAccount  cloudStorageAccount  = CloudStorageAccount::Parse(AzureStorageString); 

            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

            CloudBlobContainer cloudBlobContainer  = cloudBlobClient.GetContainerReference(folder);

            CloudBlockBlob  cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(_fileName);       

            System.IO.Stream stream = new System.IO.MemoryStream();

            cloudBlockBlob.DownloadToStream(stream, null, null, null);

            return stream;

        }

        catch

        {

            throw error(strFmt("Cannot download file to blob"));

        }

    }


    private void downloadAsZip()

    {  

        MultiSelectionHelper                helper;

        DocIntegrationHistoryTable          record;

        str                                 zipFileName;

        str                                 dateTimestamp;

 

        helper              = MultiSelectionHelper::construct();

        helper.parmDatasource(DocIntegrationHistoryTable_DS);

        record              = helper.getFirst();

        dateTimestamp =  today();       

        zipFileName = curUserId()+"_"+ dateTimestamp + ".zip";

        using(System.IO.MemoryStream zipStream  = new System.IO.MemoryStream())

        {

            using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode::Create, true))

            {

                while (record)

                {

                    // Creates the file entry in the zip folder.

                    System.IO.Compression.ZipArchiveEntry fileEntry = zipArchive.CreateEntry(record.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())

                    {

                        System.IO.Stream filestream =  BlobUtil::downloadFromBlob(record.DocumentType, record.FileName);

                        filestream.Seek(0, System.IO.SeekOrigin::Begin);

                        fileStream.CopyTo(fileEntryStream);

                        fileStream.Close();

 

                    }

                    record = helper.getNext();

                }

            }        

            File::SendFileToUser(zipStream, zipFileName );

        }     

        DocIntegrationHistoryTable_ds.refresh();

    }