Grid: Image Upload within Grid (Inline Editing)

Hi support,
I want to add a column to my grid where I can display and upload an image.
I know that this can be done with the Cell Edit Template, but I could not find any example with JavaScript.
Can you please provide an example?
I'm using the DataManager with the UrlAdaptor to make the CRUD Operations. This works very well.

Thanks in advance.

Regards,
Stephan

16 Replies

AR Arshad April 5, 2020 07:44 AM UTC



SS Stephan Schrade April 5, 2020 03:46 PM UTC

Hi support,
thanks for your answer.
But this only solves the task to display the image.

I also need the possibility to upload a new image with the "inline editor".

TIA,
Stephan


AG Ajith Govarthan Syncfusion Team April 6, 2020 12:39 PM UTC

Hi Stephan, 
 
Query:  need the possibility to upload a new image with the "inline editor". 
 
Based on your query we have prepared sample in that we have used upload component as edit template in the inline editing. Here the uploader component have save URL and uploader URL  using that you can save and remove the uploaded files by handling them at our end. We have attached the sample so please refer the sample for your reference. 
 
Code snippet:  
Index.js 
 
{ 
           headerText: 'Upload',width: 150, edit: { 
                create: function(){ 
                    elem = document.createElement('input'); 
                    return elem; 
                }, 
                read: function(args) { 
                  debugger; 
                       readfile = uploadObj.filesData[0].rawFile instanceof File ? uploadObj.filesData : readfile; 
 
        return readfile; 
                }, 
                destroy: function() { 
                    uploadObj.destroy(); 
                }, 
                write: function(args){ 
                        uploadObj = new ej.inputs.Uploader({ 
            asyncSettings: { 
     saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save', 
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove' 
            }, 
            removing: function (args) { 
                 args.postRawFile = false; 
            }, 
 
        }); 
        uploadObj.appendTo(elem); 
                } 
            } 
        } 
 

 
Regards, 
Ajith G. 



SS Stephan Schrade April 6, 2020 09:18 PM UTC

Hi support,
many thanks for your answer.
Now I managed to save the file to my server :-)
But how can I display the uploaded file within the grid?
Which url is called and which answer is expected from the server (base64 encoded file or url to the file) ?

TIA,Stephan


AG Ajith Govarthan Syncfusion Team April 7, 2020 05:42 PM UTC

Hi Stephan, 

Query: But how can I display the uploaded file within the grid? 

From the above query we need to confirm whether you want to display the uploaded image or the filename in separate column of an EJ2 Grid. 

Query: Which url is called and which answer is expected from the server (base64 encoded file or url to the file) ? 
 
We are unclear with the above lines. So, please provide more information for the above line which will help us to provide the prompt solution. 

Regards, 
Ajith G. 



SS Stephan Schrade April 7, 2020 10:38 PM UTC

Hi support,
yes I want to display the upload image within the grid.
The best would be if this can be in the same column as the upload editor.
I thought the code after "read:" is responsible for that.
And I thought that an url of the server is called in order to display the image.
That is the reason why I asked "Which url is called....."

Regards,
Stephan



AG Ajith Govarthan Syncfusion Team April 10, 2020 04:11 AM UTC

Hi Stephan, 

Sorry for the inconveniences. 

Currently we are working with your requirements that you want to upload images using inline edit and also want to show the uploaded images. Currently we are facing some complexities so we will update you on April 13th 2020. 

Regards, 
Ajith G. 



MS Manivel Sellamuthu Syncfusion Team April 14, 2020 09:50 AM UTC

Hi Stephan, 

Thanks for your patience. 

Based on your requirement we have prepared a sample.  

In the below code example we have stored the images in grid dataSource as base64 string and we displayed the images using queryCellInfo event of the Grid.  

While editing we have used cellEdit template to render the uploader. After uploading the image, we are getting the base64 string of the uploader file and save the value to the grid dataSource. 

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

ej.base.enableRipple(true); 
var gridData = require('./data'); 
    var grid = new ej.grids.Grid({ 
        dataSource: gridData, 
        queryCellInfo: queryCellInfo, 
        editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true }, 
        allowPaging: true, 
        toolbar: ['Add''Edit''Delete''Update''Cancel'], 
        columns: [ 
            { 
                field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right',width: 140 
            }, 
            { 
                field: 'CustomerID', headerText: 'Customer ID', 
                width: 140 
            }, 
            { 
                field: 'Freight', headerText: 'Freight', textAlign: 'Right', editType: 'numericedit', 
                width: 140, format: 'C2' 
            }, 
  { 
           headerText: 'Upload',field:'Image', width: 150, edit: { 
//defining the cell edit template for the image column 
                create: function(){ 
                    elem = document.createElement('input'); 
                    return elem; 
                }, 
                read: function(args) { 
// return the obtained base64 string of the image 
                  return strm; 
                }, 
                destroy: function() { 
                    uploadObj.destroy(); 
                }, 
                write: function(args){ 
                        uploadObj = new ej.inputs.Uploader({ 
            asyncSettings: { 
           saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save', 
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove' 
            }, 
// binding success and uploader events for the uploader 
          success: onUploadSuccess, 
          failure: onUploadFailure, 
        }); 
        uploadObj.appendTo(elem); 
                } 
            } 
        } 
        ], 
    }); 
    grid.appendTo('#Grid'); 
 
    function queryCellInfo (args) { 
    if (args.column.field === "Image") { 
// displaying the image store in the grid dataSource 
      args.cell.setAttribute('aria-label''image') 
      args.cell.innerText = ''; 
      var img = new Image(); 
      img.src = args.data.Image; 
      img.classList.add ('test'); 
      img.style.width='30px'; 
      img.style.height='30px'; 
      args.cell.appendChild(img); 
    } 
    } 
var strm; 
function onUploadSuccess(args) { 
  if (args.operation === 'upload') { 
// after successful upload getting the base64 string of the image 
    strm = getBase64(args.file.rawFile); 
  } 
} 
function onUploadFailure(args) { 
  console.log('File failed to upload'); 
} 
 
function getBase64(file) { 
  var reader = new FileReader(); 
  reader.readAsDataURL(file); 
  reader.onload = function () { 
    strm = reader.result; 
  }; 
  reader.onerror = function (error) { 
    console.log('Error: ', error); 
  }; 
 
} 


Please let us know if you need any further assistance. 

Regards, 
Manivel 



CE Cezar October 16, 2020 02:04 PM UTC

Is there an example of how to achieve this using Asp Net Core Razor Pages?


AG Ajith Govarthan Syncfusion Team October 20, 2020 02:09 PM UTC

Hi Cezar, 

Thanks for the update. 

Query: Is there an example of how to achieve this using Asp Net Core Razor Pages? 
 
Based on your requirement we have prepare sample with edit template for the uploader component in the ASP Net Core Razor pages. For your convenience we have attached the sample so please refer the sample for your reference. 

Code Example: 
Index.cshtml 

@page 
@model IndexModel 
@{ 
    ViewData["Title"] = "Home page"; 
} 
@Html.AntiForgeryToken() 
 
<ejs-grid id="Grid" dataSource=@Model.DataSource queryCellInfo="queryCellInfo" allowPaging="true" toolbar="@( new List<object>() {"Add","Edit","Delete","Update","Cancel"})"> 
    <e-grid-editsettings allowAdding="true" allowDeleting="true" allowEditing="true" ></e-grid-editsettings>  <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column> 
        <e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column> 
        <e-grid-column field="OrderDate" headerText="Order Date" customFormat="@(new { type ="dateTime", format="MM/dd/yyyy hh:mm:ss a" })" width="170"></e-grid-column> 
        <e-grid-column field="CustomerName" headerText="Customer Name" textAlign="Right" width="120"></e-grid-column> 
        <e-grid-column field="City" headerText="City" width="150"></e-grid-column> 
    <e-grid-column field="Image" headerText="Image" edit="@(new {create = "create", read = "read", destroy = "destroy", write = "write"})" width="150"></e-grid-column> 
    </e-grid-columns> 
</ejs-grid> 
 
 
<script> 
    var uploadObj; 
    var elem; 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function read(args) { 
 
        return strm; 
    } 
    function destroy() { 
 
        uploadObj.destroy(); 
    } 
 
    function write(args) { 
        uploadObj = new ej.inputs.Uploader({ 
            asyncSettings: { 
                saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save', 
                removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove' 
            }, 
            success: onUploadSuccess, 
            failure: onUploadFailure, 
        }); 
        uploadObj.appendTo(elem); 
    } 
 
    function queryCellInfo(args) { 
        if (args.column.field === "Image") { 
            args.cell.setAttribute('aria-label', 'image') 
            args.cell.innerText = ''; 
            var img = new Image(); 
            img.src = args.data.Image; 
            img.classList.add('test'); 
            img.style.width = '30px'; 
            img.style.height = '30px'; 
            args.cell.appendChild(img); 
        } 
    } 
    var strm; 
    function onUploadSuccess(args) { 
        if (args.operation === 'upload') { 
            strm = getBase64(args.file.rawFile); 
        } 
    } 
    function onUploadFailure(args) { 
        console.log('File failed to upload'); 
    } 
 
    function getBase64(file) { 
        var reader = new FileReader(); 
        reader.readAsDataURL(file); 
        reader.onload = function () { 
            strm = reader.result; 
        }; 
        reader.onerror = function (error) { 
            console.log('Error: ', error); 
        }; 
    } 
</script> 



Please get back to us if you need further assistance. 

Regards, 
Ajith G. 



PS psyk May 12, 2021 01:13 PM UTC

Hello,
i know i'm not it the right forums, but could you give an example for blazor .net 5 please?


RN Rahul Narayanasamy Syncfusion Team May 13, 2021 06:09 AM UTC

Hi Psyk, 
 
Greetings from Syncfusion. 
 
Query: Grid: I want to add a column to my grid where I can display and upload an image.  - , but could you give an example for blazor .net 5 please? 
 
We have validated query and we have prepared a sample in Blazor. You want to upload an image while adding/editing and show that image in Grid. We suggest you to achieve your requirement by using Column Template(for show image in Column) and EditTemplate feature(To render SfUploader for uploading the image while adding/editing) of the Grid.   
 
Here, we have shown the image in Grid columns using Column Template. For uploading the image, we have used EditTemplate. Find the below code snippets for your reference.  
 
 
<SfGrid AllowPaging="true" DataSource="@Orders" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })"> 
    <GridEvents OnActionBegin="BeginHandler" TValue="Order"></GridEvents> 
    <GridEditSettings AllowEditing="true" AllowDeleting="true" AllowAdding="true"></GridEditSettings> 
    <GridColumns> 
        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" IsPrimaryKey="true" TextAlign="@TextAlign.Center" Width="140"></GridColumn> 
        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" EditType="EditType.NumericEdit" Format="C2" Width="140" TextAlign="@TextAlign.Right"></GridColumn> 
        <GridColumn Field="Imagesrc" HeaderText="Customer Name" Width="200"> 
            <Template>          @*for showing the image in Grid column*@ 
                @{ 
                    var imageUrl = (context as Order).Imagesrc; 
                    <div class="image"> 
                        <img src="@imageUrl" /> 
                    </div> 
                } 
            </Template> 
            <EditTemplate>     @*for rendering SfUploader component in EditTemplate for uploading the image during Adding/Editing*@ 
                <SfUploader ID="uploadFiles" AllowedExtensions=".jpg,.png,.jpeg" Multiple="false"> 
                    <UploaderEvents FileSelected="Selected" ValueChange="OnChange"></UploaderEvents> 
                </SfUploader> 
            </EditTemplate> 
        </GridColumn> 
    </GridColumns> 
</SfGrid> 
 
@code{ 
    public int? DefaultValue = 100; 
    public string UploadedFile { get; set; } 
    public void BeginHandler(ActionEventArgs<Order> Args) 
    { 
        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save && Args.Action == "Add") 
        { 
            //Args.Data.OrderID = DefaultValue++;    //set the default value while adding. 
            //save the file name / url in grid datasource. You can generate the byte and store here. 
            Args.Data.Imagesrc = "scripts/Images/Employees/"+UploadedFile; 
        } else if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save && Args.Action == "Edit") 
        { 
            //save the file name / url in grid datasource. You can generate the byte and store here. 
            Args.Data.Imagesrc = "scripts/Images/Employees/" + UploadedFile; 
        } 
 
    } 
    public void Selected(SelectedEventArgs Args) 
    { 
        UploadedFile = Args.FilesData[0].Name; 
    } 
 
    public void OnChange(UploadChangeEventArgs args) 
    { 
        foreach (var file in args.Files) 
        { 
            var size = file.FileInfo.Size; 
            var path = @"./wwwroot/scripts/Images/Employees/" + file.FileInfo.Name; 
            FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write); 
            file.Stream.WriteTo(filestream); 
            filestream.Close(); 
            file.Stream.Close(); 
        } 
    } 
    . . . 
} 
 
 
 
 
Reference: 
 
Please let us know if you have any concerns. 
 
Regards, 
Rahul  



AK aujlaa karan May 13, 2021 10:22 AM UTC

I also need the possibility to upload a new image with the "inline editor".



JP Jeevakanth Palaniappan Syncfusion Team May 14, 2021 07:18 AM UTC

Hi Aujlaa , 
 
We have checked your query and we would like to inform you that the previously provided sample is to upload image in the inline editor only. So we quite unclear about your exact scenario. Please refer the video demo for your reference. 
 
 
If this is not your scenario then kindly provide us more information on your query. 
 
Regards, 
Jeevakanth SP. 



AK aujlaa karan May 25, 2021 07:56 AM UTC

many thanks for your answer.


RN Rahul Narayanasamy Syncfusion Team May 26, 2021 05:24 AM UTC

Hi Aujlaa, 
 
Thanks for the update. 
 
Please get back to us if you need further assistance. 
 
Regards, 
Rahul 


Loader.
Up arrow icon