Get file in Insert method

Hello, I am using Syncfusion grid with dialog editing, in my add dialog I have an uploader and I want to send the uploaded file in my Controller Insert method, is there any way to do that?

[View.cshtml]
<ejs-dialog id="alert_dialog" height="600px" minHeight="600px" animationSettings="defaultanimation" isModal="true" showCloseIcon="true" width="1000px" allowDragging="true">
            <e-content-template>
                <div>
                    <h5>Настан: <span id="trainingName">@Model.training.name</span></h5>
                </div>
                <ejs-grid id="Grid1" actionFailure="failure" allowResizing="true" load="onLoadDialogGrid" commandClick="commandsClickDialogGrid" toolbarClick="toolbarClickDialogGrid" actionBegin="actionBeginDialogGrid" actionComplete="actionCompleteDialogGrid" toolbar=toolbarItemsDialogGrid>
                    <e-grid-editsettings allowAdding="true" allowDeleting="true" allowEditing="true" showDeleteConfirmDialog="true" mode="Dialog"></e-grid-editsettings>
                    <e-data-manager json="Model.attachments" insertUrl="/Training/InsertAttachmentRecord" updateUrl="/Training/UpdateAttachmentRecord" removeUrl="/Training/RemoveAttachmentRecord" adaptor="RemoteSaveAdaptor"></e-data-manager>
                    <e-grid-columns>
                        <e-grid-column field="attachment_id" headerText="ID" visible="false" isPrimaryKey="true" validationRules="@(new { required=true, number=true})" width="60"></e-grid-column>
                        <e-grid-column field="file" headerText="File Name" template="#template" edit="@(new {create = "create", read = "read", destroy = "destroy", write = "write"})" width="0"></e-grid-column>
                        <e-grid-column field="fileDescription" edit="@(new {create="createTBox", read="readTBox", destroy="destroyTBox", write="writeTBox"  })" headerText="Опис на документ" width="150"></e-grid-column>
                        <e-grid-column field="fileName" headerText="Име на фајл" width="105"></e-grid-column>
                        <e-grid-column field="created" headerText="Датум" width="80"></e-grid-column>
                        <e-grid-column field="userName" headerText="Креатор" width="80"></e-grid-column>
                        <e-grid-column field="sourceTable" visible="false" headerText="Source Table" width="0"></e-grid-column>
                        <e-grid-column field="folderName" visible="false" headerText="Folder Name" width="0"></e-grid-column>
                        <e-grid-column field="sourceKey" visible="false" headerText="Source Key" width="0"></e-grid-column>
                        <e-grid-column field="training_id" visible="false" headerText="Source Key" width="0"></e-grid-column>
                        <e-grid-column field="user_id" visible="false" headerText="File Description" width="0"></e-grid-column>
                        <e-grid-column commands="commandsDialogGrid" width="60"></e-grid-column>
                    </e-grid-columns>
                </ejs-grid>
            </e-content-template>
        </ejs-dialog>


 var temp = "";
    function create(args) {
        elemUpl = document.createElement('input');
        return elemUpl;
    }
    function write(args) {
        uploadObj = new ejs.inputs.Uploader({
            success: onUploadSuccess,
            maxFileSize: 300000000000,
            uploading: onFileUpload,
        });
        uploadObj.appendTo(elemUpl);
        //console.log(uploadObj);
    }

    function destroy() {
        uploadObj.destroy();
    }

    function read(args) {
        //console.log(uploadObj.value);
        return temp;
    }
function onUploadSuccess(args) {
        if (args.operation === 'upload') {
            temp = args.file;
        }
    }

[Controller.cs]
public IActionResult InsertAttachmentRecord([FromBody]CRUDModel<Attachment> model)
        {
           //code
        }
[Model.cs]
public class Attachment
    {
        public int attachment_id { get; set; }
        public String fileName { get; set; }
        public String fileDescription { get; set; }
        public String sourceTable { get; set; }
        public int sourceKey { get; set; }
        public DateTime created { set; get; }
        public String user_id { get; set; }
        public String folderName { get; set; }
        public IFormFile file { set; get; }
        public String userName { get; set; }
        public int training_id { get; set; }
    }

7 Replies 1 reply marked as answer

PG Praveenkumar Gajendiran Syncfusion Team June 8, 2021 02:31 PM UTC

Hi Tarik, 

Thanks for contacting Syncfusion support. 

Based on your query and provided information, We have prepared a sample. In this sample, we have overridden the default functionally of adaptor and upload file during insert operation and then render file name as anchor link in grid mode using template property so you can able to download the corresponding file when click anchor link(file name) in Grid.  

By default , When we upload files in server then its needed to create a FormData and if we want to send the additional information then we have to append the value in FormData as follows, then only we  can able to get the value in controller side.  

Here, we have append the OrderID and CustomerID in FormData and get it in controller Save method(Insert method) and the insertion action was works fine and then the ModelState.IsValid  property returns the value true. Please refer the below sample, code example and screenshot for more information.

Sample: https://www.syncfusion.com/downloads/support/directtrac/166168/ze/ej2-uploader-core-services569619558.zip 

[HomeController.cs] 

 

   

Index.cshtml  
 
<div> 
    <ejs-grid id="Grid" load="load" queryCellInfo="queryCellInfo" actionComplete="complete" allowPaging="true" toolbar="@(new List<string>() { "Add", "Edit", "Cancel", "Update" })"> 
        <e-grid-editSettings allowAdding="true" allowDeleting="true" mode="Dialog"></e-grid-editSettings> 
        <e-grid-columns> 
            <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" width="150"></e-grid-column> 
            <e-grid-column field="CustomerID" headerText="CustomerID" width="150"></e-grid-column> 
            <e-grid-column field="file" headerText="File" type="string" template="#template" edit="@(new {create="fileCreate", read="fileRead", destroy="fileDestroy", write="fileWrite"  })" width="120"></e-grid-column> 
        </e-grid-columns> 
    </ejs-grid> 
</div> 
 
<script id="template" type="text/x-template"> 
    <a rel='nofollow' href=""></a> 
</script> 
 
<script> 
    var file; 
    var elem; 
    var richText; 
    var rte; 
    function queryCellInfo(args) { 
        if (args.column.field === 'file') { 
            if (args.data.file) { 
                var anchotEle = args.cell.getElementsByTagName('a')[0]; 
                anchotEle.innerText = args.data.file.name; 
                anchotEle.onclick = function click(args) { 
                    args.target.setAttribute("rel='nofollow' href", "http://localhost:63371/Home/Download?filename=" + args.target.innerText); 
                }; 
            } 
        } 
    } 
 
    function complete(args) { 
        if (args.requestType === 'add') { 
            args.form.setAttribute('enctype', 'multipart/form-data'); 
            args.form.setAttribute('encoding', 'multipart/form-data'); 
        } 
    } 
    function fileCreate() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function fileRead(args) { 
        return (file) ? file : uploadObj.filesData; 
    } 
    function fileDestroy() { 
        uploadObj.destroy(); 
    } 
    function fileWrite(args) { 
        uploadObj = new ej.inputs.Uploader({ 
            files: (args.requestType === 'beginEdit') ? [args.rowData.file] : [''] 
        }); 
        uploadObj.appendTo(elem) 
    } 
 
    function load() { 
        this.dataSource = new ej.data.DataManager({ 
            url: "/Home/UrlDatasource", 
            insertUrl: "/Home/Save", 
            updateUrl: "/Home/Update", 
            adaptor: new custom 
        }) 
    } 
    class custom extends ej.data.UrlAdaptor {  
 
        processResponse (data, ds, query, xhr, request, changes) { 
            request.data = JSON.stringify(data); 
            return ej.data.UrlAdaptor.prototype.processResponse.call(this, data, ds, query, xhr, request, changes) 
        } 
        insert(dm, data, tableName) { 
            var fd = new FormData(); 
            for (var prop of data.file) { 
                fd.append('UploadFiles', prop.rawFile); 
            } 
            fd.append('OrderID', data.OrderID); 
            fd.append('CustomerID', data.CustomerID); 
            // data.File = fd; 
            return { 
                url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url, 
                type: "POST", 
                data: fd, 
                contentType: null 
            } 
        } 
    }; 
 
</script> 

Screenshot: 
 

Please get back to us if you need further assistance. 

Regards,
Praveenkumar G  


Marked as answer

TA Tarik June 8, 2021 03:34 PM UTC

That worked for me, I want to update and remove the records the same way, can I do that with the custom adaptor?


PG Praveenkumar Gajendiran Syncfusion Team June 9, 2021 02:03 PM UTC

Hi Tarik, 

Thanks for your update. 

Based on your query,  We have prepared a sample. In this sample, we have overridden the default functionally of adaptor and upload file during insert and update operation and then render file name as anchor link in grid mode using template property so you can able to download the corresponding file when click anchor link(file name) in Grid.  

Please refer the below sample and code example for more information.

Sample: https://www.syncfusion.com/downloads/support/forum/166168/ze/ej2-uploader-core-services1444297302.zip 

[HomeController.cs]
public IActionResult Update(int OrderID, string CustomerID, IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles) 
        { 
            long size = 0; 
            if (ModelState.IsValid) 
            { 
 
            } 
            try 
            { 
                foreach (var file in UploadFiles) 
                { 
                    var filename = ContentDispositionHeaderValue 
                                    .Parse(file.ContentDisposition) 
                                    .FileName 
                                    .Trim('"'); 
                    var folders = filename.Split('/'); 
                    var uploaderFilePath = hostingEnv.WebRootPath; 
                    // for Directory upload 
                    if (folders.Length > 1) 
                    { 
                        for (var i = 0; i < folders.Length - 1; i++) 
                        { 
                            var newFolder = uploaderFilePath + $@"\{folders[i]}"; 
                            Directory.CreateDirectory(newFolder); 
                            uploaderFilePath = newFolder; 
                            filename = folders[i + 1]; 
                        } 
                    } 
                    size += file.Length; 
                    OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.OrderID == OrderID).FirstOrDefault(); 
                    val.OrderID = OrderID; 
                    val.CustomerID = CustomerID; 
                    val.file = new OrdersDetails.File() { name = filename, onlinePath = uploaderFilePath + $@"\{filename}", size = size, type = '.' + filename.Split('.')[1] }; 
                    filename = uploaderFilePath + $@"\{filename}";
                    ....
 
                } 
            } 
            catch (Exception e) 
            { 
              .... 
            } 
        } 

 
Index.cshtml  
 
<div> 
    <ejs-grid id="Grid" load="load" queryCellInfo="queryCellInfo" actionComplete="complete" allowPaging="true" toolbar="@(new List<string>() { "Add", "Edit", "Cancel", "Update" })"> 
        <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog"></e-grid-editSettings> 
        <e-grid-columns> 
            <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" width="150"></e-grid-column> 
            <e-grid-column field="CustomerID" headerText="CustomerID" width="150"></e-grid-column> 
            <e-grid-column field="file" headerText="File" type="string" template="#template" edit="@(new {create="fileCreate", read="fileRead", destroy="fileDestroy", write="fileWrite"  })" width="120"></e-grid-column> 
        </e-grid-columns> 
    </ejs-grid> 
</div> 
 
<script id="template" type="text/x-template"> 
    <a rel='nofollow' href=""></a> 
</script> 
 
<script> 
    var file; 
    var elem; 
    var richText; 
    var rte; 
    function queryCellInfo(args) { 
        if (args.column.field === 'file') { 
            if (args.data.file) { 
                var anchotEle = args.cell.getElementsByTagName('a')[0]; 
                anchotEle.innerText = args.data.file.name; 
                anchotEle.onclick = function click(args) { 
                    args.target.setAttribute("rel='nofollow' href", "http://localhost:63371/Home/Download?filename=" + args.target.innerText); 
                }; 
            } 
        } 
    } 
 
    function complete(args) { 
        if (args.requestType === 'add') { 
            args.form.setAttribute('enctype', 'multipart/form-data'); 
            args.form.setAttribute('encoding', 'multipart/form-data'); 
        }
       
// refresh the grid manually in order to reflect the changed uploader value in grid. 
        if (args.requestType === 'save' && args.action === "edit") { 
            var gridInstance = document.getElementById('Grid').ej2_instances[0]; //Grid Instance  
            gridInstance.refresh(); 
        } 
    } 
    function fileCreate() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function fileRead(args) { 
        return (file) ? file : uploadObj.filesData; 
    } 
    function fileDestroy() { 
        uploadObj.destroy(); 
    } 
    function fileWrite(args) { 
        uploadObj = new ej.inputs.Uploader({ 
            files: (args.requestType === 'beginEdit') ? [args.rowData.file] : [''] 
        }); 
        uploadObj.appendTo(elem) 
    } 
 
    function load() { 
        this.dataSource = new ej.data.DataManager({ 
            url: "/Home/UrlDatasource", 
            insertUrl: "/Home/Save", 
            updateUrl: "/Home/Update", 
            removeUrl: "Home/Delete", 
            adaptor: new custom 
        }) 
    } 
    class custom extends ej.data.UrlAdaptor {  
 
        processResponse (data, ds, query, xhr, request, changes) { 
            request.data = JSON.stringify(data); 
            return ej.data.UrlAdaptor.prototype.processResponse.call(this, data, ds, query, xhr, request, changes) 
        } 
        update(dm, data, tableName) { //update operation 
            var fd = new FormData(); 
            for (var prop of tableName.file) { 
                fd.append('UploadFiles', prop.rawFile); 
            } 
            fd.append('OrderID', tableName.OrderID); 
            fd.append('CustomerID', tableName.CustomerID); 
            // data.File = fd; 
            return { 
                url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url, 
                type: "POST", 
                data: fd, 
                contentType: null 
            } 
        } 
    }; 
 
</script> 


Please get back to us if you need further assistance. 

Regards,
Praveenkumar G  



TA Tarik June 9, 2021 09:36 PM UTC

Thank you for the quick answers, I have one more question about the dialog edit, I want to rename the Save and Cancel buttons, how can I do that?



PG Praveenkumar Gajendiran Syncfusion Team June 10, 2021 10:01 AM UTC

Hi Tarik, 
Thanks for your update. 
Based on your query, we could see that you want to localize the default text content of the Grid, for this we suggest you to set the required culture localization in the Grid(using locale property) and use the base’s L10n load function to load translation object in an application. This is demonstrated in the below code snippet,  we have set the locale culture as ‘de-DE’(German) for the Grid, 

<div> 
    <ejs-grid id="Grid" load="load" locale="de-DE"  queryCellInfo="queryCellInfo" actionComplete="complete" allowPaging="true" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })"> 
       
        <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog"></e-grid-editSettings> 
        <e-grid-columns> 
        </e-grid-columns> 
    </ejs-grid> 
</div> 
 
 
<script> 
    ej.base.L10n.load({ 
        'de-DE': { 
            'grid': { 
                'EmptyRecord': 'Keine Aufzeichnungen angezeigt', 
                'SaveButton': 'speichern', 
                'CancelButton' : 'Stornieren' 
            }, 
        } 
    }); 
</script> 


Screenshot: 
 

Refer the below doc
umentation for more information on this.

Documentation: https://ej2.syncfusion.com/aspnetcore/documentation/grid/global-local/

Please get back to us if you need further assistance.

Regards,
Praveenkumar G 



TA Tarik June 10, 2021 03:10 PM UTC

Thank you a lot, I have faced one more issue when I upload a larger file in the uploader, is there any way to upload larger files?




PG Praveenkumar Gajendiran Syncfusion Team June 11, 2021 01:02 PM UTC

Hi Tarik,

Thanks for your update.

We have created a new incident under your Direct trac account to follow up with your new query. We suggest you to follow up with the incident for further updates. Please log in using the below link.     

Regards,
Praveenkumar G 


Loader.
Up arrow icon