Business Central

Dynamics 365 Business Central – Insert or Open Attachment

If we check the business central code, we may find lot of procedures with tag [Scope(‘OnPrem’)], which means related code is not allowed to be use in development of business central extension. Here, we’ve shared source code for couple of file attachment methods which were widely used for file/attachment management. (OpenAttachment and InsertAttachment)

Insert / Upload File Attachment

procedure InsertAttachment()
var
         AttachmentRec: Record Attachment;
        FileOutStream: OutStream;
        FileInStream: InStream;
        tempfilename: text;
        DialogTitle: Label ‘Please select a File…’;
begin
        if UploadIntoStream(DialogTitle, ”, ‘All Files (*.*)|*.*’, tempfilename, FileInStream) then begin

                AttachmentRec.Init();
                AttachmentRec.Insert(true);
                AttachmentRec.”Storage Type” := AttachmentRec.”Storage Type”::Embedded;
                AttachmentRec.”Storage Pointer” := ”;
                AttachmentRec.”File Extension” := GetFileType(tempfilename);
                AttachmentRec.”Attachment File”.CreateOutStream(FileOutStream);
                CopyStream(FileOutStream, FileInStream);
                AttachmentRec.Modify(true);

        end;
end;

local procedure GetFileType(pFilename: Text): Text;
var
        FilenamePos: Integer;
begin
        FilenamePos := StrLen(pFilename);
        while (pFilename[FilenamePos] <> ‘.’) or (FilenamePos < 1) do
                FilenamePos -= 1;

        if FilenamePos = 0 then
                exit(”);

        exit(CopyStr(pFilename, FilenamePos + 1, StrLen(pFilename)));
end;

Open / Download File Attachment

procedure OpenAttachment(pFileAttachmentEntryNo: Integer)
var
        AttachmentRec: record Attachment;
        ResponseStream: InStream;
        tempfilename: text;
        ErrorAttachment: Label ‘No file available.’;
begin
        if AttachmentRec.get(pFileAttachmentEntryNo) then
              if AttachmentRec.”Attachment File”.HasValue then begin
                    AttachmentRec.CalcFields(“Attachment File”);
                    AttachmentRec.”Attachment File”.CreateInStream(ResponseStream);
                    tempfilename := CreateGuid() + ‘.’ + AttachmentRec.”File Extension”;
                    DOWNLOADFROMSTREAM(ResponseStream, ‘Export’, ”, ‘All Files (*.*)|*.*’, tempfilename);
              end
        else
              Error(ErrorAttachment);
end;

Viral Lalkiya

Sr. Software Developer

Share
Published by
Viral Lalkiya