web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

To Browse and upload file using dialog box

(1) ShareShare
ReportReport
Posted on by 1,836
hi 
i need to add one button on form and when i click the that button a dialog should open which should browse and upload file in any format how can i get this done i have can any one plz guide me on this .
I have the same question (0)
  • Suggested answer
    Martin Dráb Profile Picture
    237,681 Most Valuable Professional on at
    To Browse and upload file using dialog box
    The simplest solution is using File::getFileFromUser().
     
    If you want something more sophisticated, you can use File upload control directly, which can be used in dialogs as well. Use Find references to find examples in the standard application (such as ERFileImportUIBuilder class).
  • Suggested answer
    Layan Jwei Profile Picture
    8,097 Super User 2025 Season 2 on at
    To Browse and upload file using dialog box
    Hi Dineshkarlekar,
     
    In addition to what Martin said, check this link and see if it can help as it talks about uploading a file:
     
    Thanks,
    Layan Jweihan
  • Dineshkarlekar Profile Picture
    1,836 on at
    To Browse and upload file using dialog box
     
     hi,
    i have added button to from and written code onclicked event of it , 
    here is attachment button when we click on it diefferent form opens and when i click on new 
    i can select the type o need to attach  , like i want to attach image when i click on image .
    and upload document dialog will open and and when i select the file i will be uploded against the  record so my button will by default select the image and dialogue will open on my form and when i brouse it will upload the attacment  , i have written the code on click event of button but i am not getting datasource on form run .can you please guide me on this . 
    thanks ,
    ragards,
    Dinesh 
     
  • Martin Dráb Profile Picture
    237,681 Most Valuable Professional on at
    To Browse and upload file using dialog box
    Please elaborate your problem - it's not clear what you mean by "i am not getting datasource on form run". Also, don't forget that we don't know your code, because you didn't tell us anything about it.
  • Dineshkarlekar Profile Picture
    1,836 on at
    To Browse and upload file using dialog box
    Now i am getting this error 
    on my code , my code is below 
    final class DTPropertyDrawing
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [FormControlEventHandler(formControlStr(DTPropertyManagementSystemForm, PropertyDrawingButton), FormControlEventType::Clicked)]
        public static void PropertyDrawingButton_OnClicked(FormControl sender, FormControlEventArgs e)
        {
            DTProrpertyHeader           dtProrpertyHeader;
            FormRun                     formRun = sender.formRun() as FormRun;
            FormDataSource              dtProrpertyHeader_ds;
            DTPropertyDrawing    attach = new  DTPropertyDrawing();
            TableId                     tableid;
    
            dtProrpertyHeader_ds = sender.formRun().dataSource("DTProrpertyHeader");
            dtProrpertyHeader = dtProrpertyHeader_ds.cursor();
            tableid = tableNum(DTProrpertyHeader);
            FileUploadTemporaryStorageResult    result;
            result = file::GetFileFromUser(classStr(FileUploadTemporaryStorageStrategy));
            System.IO.Stream  sendfileStream = attach .createAttachment(tableid,dtProrpertyHeader.RecId,result);
    
        }
    
        ///Lets create the method “createAttachment()” which will do the main job of attaching the file corresponding to dtProrpertyHeader RecId.
    
        public System.IO.Stream createAttachment(TableId _refTableId, RefRecId _refRecId,FileUploadTemporaryStorageResult result)
        {
            DocuRef docuRefTable;
            DocuValue docuValueTable;
    
            Microsoft.Dynamics.AX.Framework.FileManagement.DocumentLocation              location;
            Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider      storageProvider;
            str     firstFilePath, firstFileTempPath, firstFileBase64, firstFileName, firstFileExtension;
            System.IO.Stream FileStream ;
            String20 returnMsg;
    
            FileIOPermission permission = new FileIOPermission('', 'r');
            permission.assert();
            InteropPermission interopPerm = new InteropPermission(InteropKind::ClrInterop);
            interopPerm.assert();
            DocuType fileType = DocuType::find(DocuType::typeFile());
            storageProvider = Docu::GetStorageProvider(fileType, true, curUserId());
    
            if (_refRecId > 0)
            {
                ttsBegin;
                docuValueTable.clear();
                guid FileId = newGuid();
                docuValueTable.FileId = FileId;
                docuValueTable.FileName = result.getFileName();
                docuValueTable.Name = result.getFileName();
                docuValueTable.OriginalFileName = result.getFileName();;
                container readcon = Binary::constructFromMemoryStream(result.openResult()).getContainer();
                docuValueTable.File = readcon;
                FileStream = Binary::constructFromContainer(docuValueTable.File).getMemoryStream();
                location = storageProvider.SaveFile(
                    docuValueTable.FileId,
                    storageProvider.GenerateUniqueName(docuValueTable.OriginalFileName),
                    System.Web.MimeMapping::GetMimeMapping(docuValueTable.OriginalFileName),
                    FileStream);
                if (location.NavigationUri)
                {
                    docuValueTable.Path = location.get_NavigationUri().ToString();
                }
                if (location.AccessUri)
                {
                    docuValueTable.AccessInformation = location.get_AccessUri().ToString();
                }
                docuValueTable.StorageProviderId = storageProvider.ProviderId;
                docuValueTable.insert();
                if (docuValueTable.RecId)
                {
                    docuRefTable.clear();
                    docuRefTable.RefRecId = _refRecid;
                    docuRefTable.RefTableId = _refTableId;
                    docuRefTable.RefCompanyId = curext();
                    docuRefTable.Name = result.getFileName();
                    docuRefTable.TypeId = 'File';
                    docuRefTable.ValueRecId = docuValueTable.RecId;
                    docuRefTable.insert();
                    info("File Uploaded successfully");
                }
                ttsCommit;
            }
            else
            {
                returnMsg = "Record not exit for the given Id";
            }
            return FileStream;
        }
       /// The above code will save the file to blob. Now lets get the file to the stream using code. For this we need to write a method:
            public System.IO.Stream getFilestream(DocuValueFile   _File)
            {
            System.IO.Stream   FileStream2 = Binary::constructFromContainer(_File).getMemoryStream();
            return FileStream2;
            }
        
    }
    
    plz , let me know where i am making mistake .
    thanks , 
    regards 
    Dinesh
     
     
  • Dineshkarlekar Profile Picture
    1,836 on at
    To Browse and upload file using dialog box
     i am getting the object refrence is not set to an instance of object error .
  • Martin Dráb Profile Picture
    237,681 Most Valuable Professional on at
    To Browse and upload file using dialog box
    If dtProrpetyHeader is null, it means that form doesn't contain such a data source. Are you sure that you have the typo (Prorperty instead of Property) in the data source name?  You can find these problems faster if you don't make the mistake of hard-coding objects names as strings. Instead, use methods like formDataSourceStr().
     
    Do you need an event handler at all? If it's a custom form, you could put the logic directly to clicked(), instead of using an event handler. Except of the fact that clicked() isn't a good place for business logic. When you put code directly to the form, or to an extension, you can refer to the data source simply by name. Using an event handler makes things more complicated.
     
    Another approach is putting the logic to a class (with main() method) and creating an action menu item. Then you can simply drag the menu item to a form. This allows you to use both the logic and the menu item (including the label and security permissions). In the form, you can set the Data Source property and access the record in main() by _args.record().
  • Dineshkarlekar Profile Picture
    1,836 on at
    To Browse and upload file using dialog box
    i have put the code on main() to upload attachment 
    final class DTPropertyfileUpload  
    {
        public static void main(Args _args)
        {
            FileUploadTemporaryStorageResult  result;
            DTProrpertyHeader        dtProrpertyHeader;
     
            result = File::GetFileFromUser(classStr(FileUploadTemporaryStorageStrategy));
            if(result.getUploadStatus())
            {
                str fileName = "YourFileName.jpeg"; //Insert the name of the attachchment
    
                using(System.IO.MemoryStream stream = result.openResult() as System.IO.MemoryStream)
                {
                    DocuRef docuRef = DocumentManagement::attachFile(
                                DTProrpertyHeader.TableId,
                                DTProrpertyHeader.RecId,
                                DTProrpertyHeader.DataAreaId,
                                DocuType::typeImage(),
                                stream,
                                fileName,
                                null,
                                fileName);
                }
            }
     
        }
    
    }
    but i am getting error here , and at the time of devlopement of form i  by mistake put the name Prorperty instead of Property , i have assign this class to menuitem and which will call by menu item button . can you please guide me on this .
     
  • Verified answer
    Martin Dráb Profile Picture
    237,681 Most Valuable Professional on at
    To Browse and upload file using dialog box
    You need to learn how to debug code, because that's an important part of developer's job.
     
    You called DocumentManagement::attachFile() and it threw an error. Your next step shouldn't be asking strangers on internet; instead, look at the why the error occurred. Begin by opening the definition of attachFile(). At the very top, you'll see this code:
    if (!_refTableId || !_refRecId || !_refDataAreaId || !_type || !_attachmentName || _file == null || !_fileName)
    {
        throw error(error::missingParameter(null));
    }
    This is cause - you call the method with one - or more - parameters empty.
     
    The next is finding which parameter is empty. That can be done either by using the debugger, or by reviewing your code. You can easily notice that you made the most common mistake of yours - you declared a variable (dtProrpertyHeader) and completely forgot to put any value there. You'd immediately see the bug if you didn't completely forget to debug your code.
     
    You're wasting time of both of us by not doing any attempt to debug your code. Instead of simply reviewing your code or running it in debugger, you wrote down a forum reply and keep waiting for a reply...

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 683 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 563 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 398 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans