hljs.configure({cssSelector: "code"}); hljs.highlightAll();

Monday, September 25, 2023

Download multiple attachments of sales order in one click(Zip file) Using X++ in D365FO

I have a requirement to download Sales Order attachments and send a download link to the user in One click. If there are multiple attachments available, the system will download the last attachment if we try to download file by file. To achieve this, we create a ZIP file for all the attachments and send 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;
   SalesTable  sales = SalesTable::find('000811');

   using(System.IO.MemoryStream zipStream  = new System.IO.MemoryStream())
   {
     using(System.IO.Compression.ZipArchive archive  = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode::Create, true))
     {
	  while select docuRef
	     where docuRef.RefRecId == sales.RecId
	  {
	     select docuValue where docuValue.RecId == docuRef.ValueRecId;
	     System.IO.Compression.ZipArchiveEntry dataFileEntry   = archive.CreateEntry(docuValue.filename());

	     using (System.IO.Stream dataFileEntryStream = dataFileEntry.Open())
	     {
		System.IO.Stream stream =DocumentManagement::getAttachmentStream(docuRef);
		stream.CopyTo(dataFileEntryStream);
	     }
	  }
     }
		
	File::SendFileToUser(zipStream, "Test" + '.zip');
  }
}
   

Output:


Thanks for reading!!

No comments:

Post a Comment