How To

Hide default drop area

You can achieve this behavior by overriding the corresponding uploader styles. Override the following styles to hide the default drop area behavior.

* .e-upload.e-control
* .e-upload .e-file-select
* .e-upload .e-file-drop
razor
hide-drop.cs
index.css
@section ControlsSection{
    
      @Html.EJS().Uploader("UploadFiles").DropArea(".control-fluid").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}
#droparea {
    padding: 50px 25px;
    margin: 30px auto;
    border: 1px solid #c3c3c3;
    text-align: center;
    width: 20%;
    display: inline-flex;
    }
    .e-file-select,
    .e-file-drop {
    display: none;
    }
    body .e-upload-drag-hover {
    outline: 2px dashed brown;
    }
    #uploadfile {  
    width: 60%;
    display: inline-flex;
    margin-left: 5%;
    }
	.e-control .e-file-select,
	.e-control .e-file-drop {
	  display: none;
	}

Preview images before uploading

The uploader component allows to create preview images before uploading. The preview images can be created by reading the file using selected event. Also, the user can create preview images after uploading to server using success event. Refer to the following link to learn about how to create image preview.

Image Preview in MVC

Achieve invisible upload

You can achieve the invisible upload feature by using the selected event in uploader component. Refer to the following example.

razor
invisible.cs
@section ControlsSection{
    
      <div class="control_wrapper">
       <div id='preview'></div>
      
            @Html.EJS().Uploader("UploadFiles").AllowedExtensions(".png, .jpg, .jpeg").Selected("onSelect").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
            
      </div>

}

@section PreScripts {
<script>
      function onSelect(args) {
      for (var i = 0; i < args.filesData.length; i++) {
            var liparentDiv = ej.base.createElement('div', { className: 'image-list' });
            var liImage = ej.base.createElement('img', { className: 'image' });
            liparentDiv.appendChild(liImage);
            readURL(liImage, args.filesData[i]);
            document.getElementById('preview').appendChild(liparentDiv);
      }
      args.cancel = true;
      }
      
      function readURL(liImage, file) {
      var imgPreview = liImage;
      var imageFile = file.rawFile;
      var reader = new FileReader();
      reader.addEventListener('load', () => {
            imgPreview.src = reader.result;
      }, false);
      if (imageFile) {
            reader.readAsDataURL(imageFile);
      }
      }
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Customize progressbar

You can customize the progress bar’s size, color, and background by overriding the styles in uploader component. Refer to the following example.

razor
progress-customize.cs
@using Syncfusion.EJ2

@section ControlsSection{

      <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
      </div>

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Sort the selected files

You can sort the selected files in uploader component by using the selected event. Refer to the following example.

razor
sorting.cs
@using Syncfusion.EJ2

@section ControlsSection{

      <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").Selected("onSelect").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
        </div>

}

<script>
    var initial = true
    function onSelect(args) {
        if (initial) { initial = false; return; }
        args.isModified = true;
        var oldFiles = uploadObj.getFilesData();
        var filesData = args.filesData.concat(oldFiles);
        var modifiedData = sortFileList(filesData);
        args.modifiedFilesData = modifiedData;
    }

    function sortFileList(filesData) {
        var files = filesData;
        var fileNames = [];
        for (var i = 0; i < files.length; i++) {
            fileNames.push(files[i].name);
        }
        var sortedFileNames = fileNames.sort();
        var sortedFilesData = [];
        var index = 0;
        for (var i = 0; i < sortedFileNames.length; i++) {
            var name = sortedFileNames[i];
            for (var i = 0; i < files.length; i++) {
                if (name === files[i].name) {
                    sortedFilesData.push(files[i]);
                }
            }
        }
        return sortedFilesData;
    }

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Get the total size of selected files

You can get the total size of selected files before uploading it to the designated server. This can be achieved by using the selected event. Refer to the following example to calculate the total file size.

razor
file-size.cs
@using Syncfusion.EJ2

@section ControlsSection{

      <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").Selected("onSelect").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove") }).Render()
        </div>

}

<script>
    function onSelect(args) {
        var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
        var totalSize = 0;
        for (var i = 0; i < args.filesData.length; i++) {
            var file = args.filesData[i];
            totalSize = totalSize + file.size;
        }
        var size = uploadObj.bytesToSize(totalSize);
        alert("Total select file's size is " + size);
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Customize button with HTML element

The uploader component allows you to customize the action buttons by using buttons  property. Refer to the following example.

razor
buttons.cs
@using Syncfusion.EJ2

@section ControlsSection{

<div class="control_wrapper">
        @Html.EJS().Uploader("UploadFiles").AutoUpload("false").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
</div>

}

<script>
    var uploadEle = ej.base.createElement('span', { className: 'upload e-icons' });
    uploadEle.innerHTML = 'Upload All';
    var clearEle = ej.base.createElement('span', { className: 'remove e-icons' });
    clearEle.innerHTML = 'Clear All';
    window.onload = function (args) {        
    var uploaderObj = document.getElementById("UploadFiles").ej2_instances[0];
    uploaderObj.setProperties({
        buttons: {
            browse: 'Choose file',
            clear: clearEle,
            upload: uploadEle
        }})
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Output be like the below.

uploader

Add confirm dialog to remove the files

You can customize the uploader component using confirm dialog before removing the files. Here, ej2 dialog is used as confirm dialog. Refer to the following example.

razor
confirm-dialog.cs
index.css
@using Syncfusion.EJ2

@section ControlsSection{

    <div class="control_wrapper">
        @Html.EJS().Uploader("UploadFiles").Removing("onremove").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove"}).Render()
        @Html.EJS().Dialog("dialog").Target(".control-section").Visible(false).Width("250px").Content("Confirm to remove the file?").Buttons(ViewBag.DefaultButtons).Render()
    </div>

}

<script>

    var removeFile = [], dialog;

    window.onload = function () {
        dialog = document.getElementById("dialog").ej2_instances[0];
    }

    function onremove(args) {
        args.cancel = true;
        removeFile.push(args.filesData);
        dialog.show();
    }

    function onClick(args) {
        var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
        dialog.hide();
        uploadObj.remove(removeFile, false, true);
        removeFile = [];
    }

    function Close() {
        dialog.hide();
    }

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            ViewBag.button = new
            {
                content = "Ok",
                isPrimary = true
            };
            
            return View();
        }
    }
}
.control_wrapper {
    max-width: 400px;
    margin: 0 auto;
}

Add additional data on upload

The uploader component allows you to add additional data on file upload, which is used to get in the server-side. By using uploading event and its customFormData argument, you can achieve this behavior. Refer to the following example.

razor
index.css
@using Syncfusion.EJ2

@section ControlsSection{

<div class="control_wrapper">

      @Html.EJS().Uploader("fileupload").Uploading("onFileUpload").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
      
</div>

}

@section PreScripts {
<script>
function onFileUpload(args) {
  args.customFormData = [{'name': 'Syncfusion INC'}];
}
</script>
}
.control_wrapper {
	max-width: 505px;
	margin: auto;
}

Validate image/* on drop

The uploader component allows you to select all types of images using the *image/ ** to allowedExtensions property. You can directly set it to accept the attribute of uploader element.

By default, it is working fine when you select a file by clicking the browse button. But, this behavior is not supported to drag and drop the files for selection.

razor
validate-image.cs
index.css
@using Syncfusion.EJ2

@section ControlsSection{

<div class="control_wrapper">
      @Html.EJS().Uploader("fileupload").AutoUpload(false).AllowedExtensions("image/*").Selected("onSelect").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()     
</div>

}

@section PreScripts {
<script>
function onSelect(args) {
      var uploadObj = document.getElementById("fileupload").ej2_instances[0];
      if (event.type === 'drop') {
      var allImages = ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bpg'];
      var files = args.filesData;
      var modifiedFiles = [];
      for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (allImages.indexOf(file.type) === -1) {
                  file.status = 'File type is not allowed';
                  file.statusCode = '0';
            }
            modifiedFiles.push(file);
      }
      args.isModified = true;
      args.modifiedFilesData = modifiedFiles.concat(uploadObj.filesData);
      }
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}
.control_wrapper {
	max-width: 505px;
	margin: auto;
}

Determine whether uploader has file input (required validation)

By setting required attribute to uploader input element, you can validate the file input has any value in it. In the below sample, set required attribute to the uploader input element and showcase the validation failure message using data-required-message attribute.

razor
required.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups

    <div class="col-lg-8 control-section">
        <div class="control_wrapper">
            <div class="col-lg-12 control-section">
                <h4 class="form-title">Photo Contest</h4>
                <div class="control_wrapper" id="control_wrapper">
                    <form id="form1" method="post">
                        <div class="form-group" style="padding-top: 40px; float: left">
                            <div class="e-float-input">
                                <input type="text" id="name" name="name" data-required-message="* Enter your name" required="" data-msg-containerid="nameError">
                                <span class="e-float-line"></span>
                                <label class="e-float-text e-label-top" for="name">Name</label>
                            </div>
                            <div id="nameError"></div>
                        </div>
                        <div id="dropArea">
                            <div id="uploadError" style='float: right;'></div>
                            <div id='customBrowse' class="form-group dropUpload">
                                Drop image here...
                                @Html.EJS().Uploader("fileupload").DropArea(".dropUpload").Selected("onFileSelect").AllowedExtensions("image/*").Multiple(true).AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
                            </div>
                        </div>
                        <div class="submitBtn">
                            <button type="button" class="submit-btn e-btn" id="submit-btn">Submit</button>
                            <div class="desc"><span>*This button is not a submit type and the form submit handled from externally.</span></div>
                        </div>
                    </form>
                    @Html.EJS().Dialog("confirmationDialog").Buttons(ViewBag.dlgButtons).Width("335px").Visible(false).Content("Your details has been updated successfully, Thank you").OverlayClick("closeDialog").Target("#control_wrapper").IsModal(true).AnimationSettings(new DialogAnimationSettings() { Effect = DialogEffect.Zoom }).Render()
                </div>
            </div>
        </div>
    </div>

<script>
    var formID, confirm;
    window.onload = function () {
        inputElement = document.getElementById('upload');
        formID = document.getElementById('form1');
        confirm = document.getElementById("confirmationDialog").ej2_instances[0];
        formObj = new ej.inputs.FormValidator(formID, options);
        document.getElementById('customBrowse').onclick = () => {
            document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
        };
        document.getElementById('submit-btn').onclick = () => {
            onFormSubmit();
        };
    }
    var options = {
        customPlacement: function (inputElement, errorElement) {
            inputElement = inputElement.closest('.form-group').querySelector('.error');
            inputElement.parentElement.appendChild(errorElement);
        },
        rules: {
            'name': {
                required: true
            }
        }
    };
    function onFileSelect(args) {
        if (args.filesData.length > 0) {
            if (document.getElementsByClassName('upload-image').length > 0) {
                detach(document.getElementsByClassName('imgWrapper')[0]);
            }
            var imageTag = ej.base.createElement('IMG', { className: 'upload-image', attrs: { 'alt': 'Image' } });
            var wrapper = ej.base.createElement('span', { className: 'imgWrapper' });
            wrapper.appendChild(imageTag);
            var rootFile = document.getElementsByClassName('dropUpload')[0];
            rootFile.insertBefore(wrapper, rootFile.firstChild);
            readURL(wrapper, args.filesData[0]);
        }
        args.cancel = true;
    }

    function readURL(li , args) {
        var preview = li.querySelector('.upload-image');
        var file = args.rawFile;
        var reader = new FileReader();
        reader.addEventListener('load', () => { preview.src = reader.result; }, false);
        if (file) { reader.readAsDataURL(file); }
    }
    var options = {};
    formID = document.getElementById('form1');
    var formObj = new ej.inputs.FormValidator(formID, options);
    function onFormSubmit() {
        var formStatus = formObj.validate();
        if (formStatus) {
            formObj.element.reset();
            ej.base.detach(document.getElementsByClassName('imgWrapper')[0]);
            confirm.show();
        }
		document.querySelector('#UploadFiles').setAttribute('data-required-message', '* Choose your image to upload');
		document.querySelector('#UploadFiles').setAttribute('required', '');
		document.querySelector('#UploadFiles').setAttribute('data-msg-containerid', 'uploadError');

    }
    function closeDialog() {
        confirm.hide();
    }
   
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            ViewBag.button = new
            {
                content = "Ok",
                isPrimary = true
            };
            
            return View();
        }
    }
}

Achieve file upload programmatically

You can upload a file programmatically using upload method. The selected files data, get from getFilesData public method in uploader.

The upload method behaves differently based on its arguments.

  • If this method receives any files as arguments, those files only start to upload.
  • If it has no argument then all the selected files are will start to upload.
razor
dynamic-upload.cs
index.css
@using Syncfusion.EJ2

<div class="col-lg-8 control-section">
        <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").AutoUpload(false).DropArea(".control-fluid").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
        </div>
        <span style=' padding-left: 40px; margin-top: 30px'>
            <button id='first' class='e-btn e-control'>Upload 0th File</button>
        </span>
        <span style=' padding-left: 40px; margin-top: 30px'>
            <button id='full' class='e-btn e-control'>Upload All Files</button>
        </span>
</div>

<script>

 window.onload = function () {
        var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
        document.getElementById('first').onclick = (args) => {
            uploadObj.upload(uploadObj.getFilesData()[0]);
        };

        document.getElementById('full').onclick = (args) => {
            uploadObj.upload(uploadObj.getFilesData());
        };
    }

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            
            return View();
        }
    }
}
.control_wrapper {
        max-width: 500px;
        margin: auto;
    }

    .e-upload {
        width: 100%;
        position: relative;
        margin-top: 15px;
        margin-bottom: 15px;
    }

    .e-upload-actions {
        display: none;
    }

    .e-btn {
        text-transform: none;
    }

    .control_wrapper .e-upload .e-upload-drag-hover {
        margin: 0;
    }

Check file size before uploading it

By using uploading event, you can get the file size before upload it to server. File object contains the file size in bytes only. You can convert the size to standard formats (KB or MB) using bytesToSize method.

razor
check-file-size.cs
index.css
@using Syncfusion.EJ2

 <div class="col-lg-8 control-section">
        <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").Uploading("onBeforeUpload").AutoUpload(false).DropArea(".control-fluid").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
        </div>
    </div>

<script>
 
 function onBeforeUpload(args) {
        var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
        // get the file size in bytes
        var sizeInBytes = args.fileData.size;
        // get the file size in standard format
        alert("File size is: " + uploadObj.bytesToSize(sizeInBytes))
    }

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            
            return View();
        }
    }
}
.control_wrapper {
        max-width: 500px;
        margin: auto;
    }

    .control_wrapper .e-upload .e-upload-drag-hover {
        margin: 0;
    }

Check the MIME type of file before upload it

By using uploading event, you can get the file MIME type before uploading it to server. In the below sample, file MIME type is shown in the alert box before file start to upload.

razor
mime-type.cs
index.css
@using Syncfusion.EJ2

 <div class="col-lg-8 control-section">
        <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").Uploading("onBeforeUpload").AutoUpload(false).DropArea(".control-fluid").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
        </div>
    </div>

<script>
 
function onBeforeUpload(args) {
	// get the file MIME type
	alert("File MIME type is: " + args.fileData.rawFile.type);
}

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            
            return View();
        }
    }
}
.control_wrapper {
        max-width: 500px;
        margin: auto;
    }

    .control_wrapper .e-upload .e-upload-drag-hover {
        margin: 0;
    }

Trigger click event of input file from external button

You can trigger the click event of input file from external button using click event of button. In the below sample, triggered click event of input file from Essential JavaScript 2 Button.

razor
external-click.cs
index.css
@using Syncfusion.EJ2

 <div class="col-lg-8 control-section">
        <div class="control_wrapper">
            <div id="dropArea">
                <span id="drop"> Drop image (JPG, PNG) files here or <button class='e-btn e-control' id="browse">Browse</button></span>
            </div>
            @Html.EJS().Uploader("UploadFiles").DropArea("#drop").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
        </div>
    </div>

<script>

 window.onload = function () {
	document.getElementById('browse').onclick = () => {
		document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
	};
}

</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            
            return View();
        }
    }
}
.control_wrapper {
        max-width: 500px;
        margin: auto;
    }
    #dropArea {
        border: 1px dashed #c3c3cc;
        text-align: center;
        padding: 20px 0 10px;
    }

    .e-file-select-wrap {
        display: none;
    }

    .control_wrapper .e-upload .e-upload-drag-hover {
        margin: 0;
    }

Open and edit the uploaded files

The uploader component allows you to modify the file after uploading to the server, which can be achieved using success event of the uploader.

You can retrieve the saved file path in the uploader success event and assign it to custom attribute (data-file-name) value of the respective file list element to open the uploaded file. Click the respective file element to create a new request along with saved file path using http header. In the server-side, get the file path from the header and open the file using process.start method.

razor
server-side.cs
@using Syncfusion.EJ2

@section ControlsSection{

      <div class="control_wrapper">
            @Html.EJS().Uploader("UploadFiles").Success("onUploadSuccess").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
        </div>

}

<script>
   function onUploadSuccess(args) {
    // fetching the generated li elements
    var liElements = this.uploadWrapper.querySelectorAll('.e-upload-file-list');
    for (var i = 0; i < liElements.length; i++) {
        if (liElements[i].getAttribute('data-file-name') == args.file.name) {
            liElements[i].addEventListener('click', () => { openFile(args, event) })
            // File path have to update from server end in response status description.
            liElements[i].setAttribute('file-path', args.e.target.statusText);
        }
    }
}

function openFile(args, e) {
    if (!e.target.classList.contains('e-file-delete-btn') && !e.target.classList.contains('e-file-remove-btn'))
    {
        var ajax = new XMLHttpRequest();
        // create new request for open the selected file
        ajax.open("POST", '/Home/openFile');
        var liElements = document.getElementsByClassName('e-upload')[0].querySelectorAll('.e-upload-file-list');
        for (var i = 0; i < liElements.length; i++) {
            if (liElements[i].getAttribute('data-file-name') == args.file.name) {
                // Added the file path in header to get it in server side.
            ajax.setRequestHeader('filePath', liElements[i].getAttribute('file-path').toString());
            }
        }
        ajax.send();
    }
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public IActionResult DefaultFunctionalities()
        {
            return View();
        }
        public void Save() {
    if (!System.IO.File.Exists(fileSavePath))
    {
        httpPostedFile.SaveAs(fileSavePath);
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        <!-- Sending the file path to client side -->
        Response.StatusDescription = fileSavePath;
        Response.End();
    }
}

[AcceptVerbs("Post")]
public void openFile()
{
    // Check whether the file is available in the corresponding location
    if (System.IO.File.Exists(Request.Headers.GetValues("filePath").First()))
    {
        // This will open the selected file from server location in desktop
        Process.Start(Request.Headers.GetValues("filePath").First());
    }
}
    }
}

Resize images before uploading it to the server

You can customize the dimension of the images before uploading it to the server. By using selected event, you can get the selected file information as type of an object. From the obtained image file information, create a new canvas and render an image with the custom dimensions. Refer the corresponding code snippet as follows.

razor
pre-resize.cs
@using Syncfusion.EJ2
<div id='dropArea'>
    <span id='drop' class="droparea"> Drop files here or <a href="" id='browse'><u>Browse</u></a> </span>
    @Html.EJS().Uploader("UploadFiles").DropArea("#dropArea").Selected("onFileSelect").Progress("onFileUpload").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("/Uploader/Remove") }).AllowedExtensions("image/*").Success("onUploadSuccess").Removing("onFileRemove").Failure("onUploadFailed").Render()
</div>

<script>
    var uploadObj;
    window.onload = function () {
        uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
    }
    document.getElementById('browse').onclick = function () {
        document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
        return false;
    };
    var parentElement; var proxy; var progressbarContainer;
    function onFileSelect(args) {
        args.cancel = true;
        if (ej.base.isNullOrUndefined(document.getElementById('dropArea').querySelector('.upload-list-root'))) {
            parentElement = ej.base.createElement('div', { className: 'upload-list-root' });
            parentElement.appendChild(ej.base.createElement('ul', { className: 'ul-element' }));
            document.getElementById('dropArea').appendChild(parentElement);
        }
        for (var i = 0; i < args.filesData.length; i++) {
            formSelectedData(args.filesData[i], this);    // create the LI element for each file Data
        }
        this.filesData = this.filesData.concat(args.filesData);
        var file = args.filesData[0].rawFile;
        var width;
        var height;
        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onload = function (e) { img.src = e.target.result; };
        reader.readAsDataURL(file);
        var imgs = new Image();
        img.onload = function () {
            width = this.width;
            height = this.height;
            onNewImg(height, width, img, args.filesData[0]);
        };
        imgs.src = img.src;
        
    }
    // to create canvas and update our custom dimensions
    function onNewImg(height, width, img, file) {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var MAX_WIDTH = 1000;
        var MAX_HEIGHT = 600;
        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        }
        else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx1 = canvas.getContext("2d");
        ctx1.drawImage(img, 0, 0, width, height);
        newImage = canvas.toDataURL("image/png");
        var blobBin = atob(newImage.split(',')[1]);
        var array = [];
        for (var i = 0; i < blobBin.length; i++) {
            array.push(blobBin.charCodeAt(i));
        }
        var newBlob = new Blob([new Uint8Array(array)], { type: 'image/png' });
        var newFile = createFile(newBlob, file);
        uploadObj.upload(newFile, true);
    }
    // To create File object to upload
    function createFile(image, file) {
        var newFile = {
            name: file.name,
            rawFile: image,
            size: image.size,
            type: file.type,
            validationMessage: '',
            statusCode: '1',
            status: 'Ready to Upload'
        };
        return newFile;
    }
    function formSelectedData(selectedFiles, proxy) {
        var liEle = ej.base.createElement('li', { className: 'file-lists', attrs: { 'data-file-name': selectedFiles.name } });
        liEle.appendChild(ej.base.createElement('span', { className: 'file-name ', innerHTML: selectedFiles.name }));
        liEle.appendChild(ej.base.createElement('span', { className: 'file-size ', innerHTML: proxy.bytesToSize(selectedFiles.size) }));
        if (selectedFiles.status === proxy.localizedTexts('readyToUploadMessage')) {
            progressbarContainer = ej.base.createElement('span', { className: 'progress-bar-container' });
            progressbarContainer.appendChild(ej.base.createElement('progress', { className: 'progress', attrs: { value: '0', max: '100' } }));
            liEle.appendChild(progressbarContainer);
        }
        else {
            liEle.querySelector('.file-name').classList.add('upload-fails');
        }
        var closeIconContainer = ej.base.createElement('span', { className: 'e-icons close-icon-container' });
        ej.base.EventHandler.add(closeIconContainer, 'click', removeFiles, proxy);
        liEle.appendChild(closeIconContainer);
        document.querySelector('.ul-element').appendChild(liEle);
        proxy.fileList.push(liEle);
    }
    function onFileUpload(args) {
        var li = document.getElementById('dropArea').querySelector('[data-file-name="' + args.file.name + '"]');
        ej.base.EventHandler.remove(li.querySelector('.close-icon-container'), 'click', removeFiles);
        var progressValue = Math.round((args.e.loaded / args.e.total) * 100);
        if (!isNaN(progressValue)) {
            li.getElementsByTagName('progress')[0].value = progressValue;   // Updating the progress bar value
        }
    }
    function onUploadSuccess(args) {
        var _this = this;
        var spinnerElement = document.getElementById('dropArea');
        var li = document.getElementById('dropArea').querySelector('[data-file-name="' + args.file.name + '"]');
        if (!ej.base.isNullOrUndefined(li.querySelector('.progress-bar-container'))) {
            ej.base.detach(li.querySelector('.progress-bar-container'));
        }
        if (args.operation === 'upload') {
            li.querySelector('.file-name').classList.add('upload-success');
            li.querySelector('.close-icon-container').classList.add('delete-icon');
            (li.querySelector('.close-icon-container')).onclick = function () {
                generateSpinner(_this.uploadWrapper);
            };
            li.querySelector('.close-icon-container').onkeydown = function (e) {
                if (e.keyCode === 13) {
                    generateSpinner(e.target.closest('.e-upload'));
                }
            };
        }
        if (args.operation === 'remove') {
            this.filesData.splice(this.fileList.indexOf(li), 1);
            this.fileList.splice(this.fileList.indexOf(li), 1);
            ej.base.detach(li);
            ej.popups.hideSpinner(spinnerElement);
            ej.base.detach(spinnerElement.querySelector('.e-spinner-pane'));
        }
        ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', removeFiles, this);
        console.log("The selected file resized and uploaded successfully");
    }
    function generateSpinner(targetElement) {
        ej.popups.createSpinner({ target: targetElement, width: '25px' });
        ej.popups.showSpinner(targetElement);
    }
    function onUploadFailed(args) {
        var li = document.getElementById('dropArea').querySelector('[data-file-name="' + args.file.name + '"]');
        ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', removeFiles, this);
        li.querySelector('.file-name ').classList.add('upload-fails');
        if (args.operation === 'upload') {
            ej.base.detach(li.querySelector('.progress-bar-container'));
        }
    }
    function removeFiles(args) {
        var status = this.filesData[this.fileList.indexOf(args.currentTarget.parentElement)].status;
        if (status === this.localizedTexts('uploadSuccessMessage')) {
            this.remove(this.filesData[this.fileList.indexOf(args.currentTarget.parentElement)], true);
        }
        else {
            ej.base.detach(args.currentTarget.parentElement);
        }
    }
    function onFileRemove(args) {
        args.postRawFile = false;
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.Uploader
{
    public partial class UploaderController : Controller
    {
        public IActionResult Template()
        {
            return View();
        }
    }
}

Convert image into binary format after uploading

By default, the file upload control saves the uploaded image files in physical directories. Also, you can convert the images into binary format at server-side before saving the uploaded images. To retrieve binary format of image files, convert the posted file’s input stream into binary reader and read as bytes using ReadBytes method.

Refer to the below server-side code snippet

[AcceptVerbs("Post")]
public void Save()
{
    try
    {
        if (System.Web.HttpContext.Current.Request.Files.AllKeys.Length > 0)
        {
            var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadFiles"];

            if (httpPostedFile != null)
            {
                byte[] fileBytes;
                using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream))
                {
                    fileBytes = br.ReadBytes((int)httpPostedFile.InputStream.Length);
                    // bytes will be stored in variable fileBytes
                }
                HttpResponse Response = System.Web.HttpContext.Current.Response;
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusCode = 200;
                Response.Status = "200 Success";
                Response.End();
            }
        }
    }
    catch (Exception e)
    {
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.StatusCode = 204;
        Response.Status = "204 No Content";
        Response.StatusDescription = e.Message;
        Response.End();
    }
}