Hi, Readers.
Today I would like to talk about how to limit (block) the specific file types/format for uploading attachment in Business Central.
In the FactBox on most cards and documents, you can attach any type of file, containing text, image, or video, to a card or document. This is useful, for example, when you want to store a customer’s invoice as a PDF file on the related sales invoice in Business Central.


There is a small problem here. By default, all types of files can be uploaded.

Is there a way to restrict it? For example, only allow uploading PDF or Image? Yes, but this is not a standard feature, we need to do a little customization. In this post, I will share a simple way that I hope will help you.
The event we can use this time is ‘OnBeforeInsertAttachment‘ in table 1173 “Document Attachment”. (Please note this is not the only solution)


Let’s look at a simple test.

Test Code:
codeunit 50111 LimitAttachmentType
{
[EventSubscriber(ObjectType::Table, Database::"Document Attachment", OnBeforeInsertAttachment, '', false, false)]
local procedure OnBeforeInsertAttachment(var DocumentAttachment: Record "Document Attachment");
begin
Message(StrSubstNo('File Extension is %1', DocumentAttachment."File Extension"));
Message(StrSubstNo('File Type is %1', DocumentAttachment."File Type"));
end;
}
Using this event, we can get the extension and type of the file.



File Type is classified by File Extension.


So we can control it through File Type or File Extension. Let’s go back to the requirement mentioned at the beginning, only allowing users to upload only image and pdf files.

Test code:
codeunit 50111 LimitAttachmentType
{
[EventSubscriber(ObjectType::Table, Database::"Document Attachment", OnBeforeInsertAttachment, '', false, false)]
local procedure OnBeforeInsertAttachment(var DocumentAttachment: Record "Document Attachment");
begin
if not (DocumentAttachment."File Type" in [DocumentAttachment."File Type"::"Image", DocumentAttachment."File Type"::PDF]) then
Error('You can only attach an image file or a pdf file.');
end;
}

Test video:
Very simple, you can also add a setting to add file types that the user should allow or not allow. Give it a try!!!😁
PS: Dynamics 365 Business Central: How to limit max file size for uploading attachment (Customization)
END
Hope this will help.
Thanks for your reading.
ZHU
コメント