Asynchronous upload

25 Feb 202220 minutes to read

The uploader control allows you to upload the files asynchronously.
The upload process requires save and remove action URL to manage the upload process in the server.

*   The save action is necessary to handle the upload operation.
*   The remove action is optional, one can handle the removed files from server.

The File can be uploaded automatically or manually. For more information, you can refer to the Auto Upload section from the documentation.

Multiple file upload

By Default, the uploader control allows you to select and upload multiple files simultaneously.
The selected files are organized in a list for every file selection until you clear it by clicking clear button that is shown in footer. You can add the multiple attributes to original input element of file by enabling the multiple file selection.
The following example explains about multiple file upload settings.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" autoUpload="false"></ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Single file upload

You can select and upload a single file by disabling the multiple file selection property.
The file list item is removed for every selection and it always maintain a single file to upload.
You can remove the multiple attributes form the original input element of file by enabling the single file upload property.

The following example explains about single file upload settings.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" multiple="false" autoUpload="false"></ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Save action

The save action handler upload the files that needs to be specified in the saveUrl property.
The save handler receives the submitted files and manages the save process in server.
After uploading the files to server location, the color of the selected file name changes to green and the remove icon is changed as bin icon.

*   When the file is uploaded successfully, the event “success” triggers to handle the operation after upload.
*   When the file is failed to upload, the event “failure” triggers with information, which cause this failure.

You can cancel the upload process by setting the upload event argument eventargs.cancel to true.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" autoUpload="false"></ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Server-side configuration for save action

This section explains how to handle the server-side action for saving the file from server.

private IHostingEnvironment hostingEnv;

public UploaderController(IHostingEnvironment env)
{
    this.hostingEnv = env;
}

// Upload method for chunk-upload and normal upload
public void Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
{
    long size = 0;
    try
    {
        // for chunk-upload
        foreach (var file in chunkFile)
        {
            var filename = ContentDispositionHeaderValue
                                .Parse(file.ContentDisposition)
                                .FileName
                                .Trim('"');
            filename = hostingEnv.WebRootPath + $@"\{filename}";
            size += file.Length;

            if (!System.IO.File.Exists(filename))
            {
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
            else
            {
                using (FileStream fs = System.IO.File.Open(filename, FileMode.Append))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 204;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }

    // for normal upload
    try
    {
        foreach (var file in UploadFiles)
        {
            var filename = ContentDispositionHeaderValue
                            .Parse(file.ContentDisposition)
                            .FileName
                            .Trim('"');
            filename = hostingEnv.WebRootPath + $@"\{filename}";
            size += file.Length;
            if (!System.IO.File.Exists(filename))
            {
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 204;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}

Remove action

The remove action is optional. Specify the URL to handle remove process from server.
The remove handler receives the posted files and handle the remove operation in server.

*   When the files are removed successfully from the server, the success event triggers to denote the process has completed.
*   When remove action fails, the event [failure](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Inputs.Uploader.html#Syncfusion_EJ2_Inputs_Uploader_Failure) triggers with information, which cause failure in remove process.

You can differentiate the file operation whether the success event triggers from save or remove action in its arguments eventArgs.operation.

You can remove the files which is not uploaded locally by clicking the remove icon. In this case, the success or failure events will not be triggered.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" autoUpload="false"></ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Server-side configuration for remove action

This section explains how to handle the server-side action for removing the file from server.

private IHostingEnvironment hostingEnv;

public HomeController(IHostingEnvironment env)
{
    this.hostingEnv = env;
}
// to delete uploaded chunk-file from server
public void Remove(IList<IFormFile> UploadFiles)
{
    try
    {
        var filename = hostingEnv.WebRootPath + $@"\{UploadFiles[0].FileName}";
        if (System.IO.File.Exists(filename))
        {
            System.IO.File.Delete(filename);
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 200;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}

Set the argument in the Remove method to string type, which contains the file name, while setting the postRawFile to false in the removing event.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" removing="onFileRemove"></ejs-uploader>
<script>
    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.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}
private IHostingEnvironment hostingEnv;

public HomeController(IHostingEnvironment env)
{
    this.hostingEnv = env;
}
// to delete uploaded chunk-file from server
public void Remove(string UploadFile)
{
    try
    {
        var filename = hostingEnv.WebRootPath + $@"\{UploadFile}";
        if (System.IO.File.Exists(filename))
        {
            System.IO.File.Delete(filename);
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 200;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}

Auto upload

By default, the uploader processes the files to upload once the files are selected and added in upload queue. To upload manually, disable the autoUpload property. When you disable this property, you can use the action buttons to call upload all or clear all actions manually. You can change those buttons text using the buttons property in Uploader control.

<ejs-uploader id="uploadFiles" autoUpload="false"></ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Auto upload output be like the below.

uploader

Auto upload false output be like the below.

uploader

Sequential upload

By default, the uploader control process multiple files to upload simultaneously. When you enable the sequentialUpload property, the selected files will process sequentially (one after the other) to the server. If the file uploaded successfully or failed, the next file will upload automatically in this sequential upload. This feature helps to reduce the upload traffic and reduce the failure of file upload.

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}

<ejs-uploader id="uploadFiles" sequentialUpload="true" asyncSettings="@asyncSettings"></ejs-uploader>
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 ActionResult SequentialUpload()
        {
            return View();
        }
    }
}

Preload files

The uploader control allows you to preload the list of files that are uploaded in the server. The preloaded files are useful to view and remove the files from server that can be achieved by the files property. By default, the files are configured with uploaded successfully state on rendering file list. The following properties are mandatory to configure the preloaded files:

*   Name
*   Size
*   Type
@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}

<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings">
    <e-uploader-files>
        <e-uploader-uploadedfiles name="Books" Size=500000 type=".png"></e-uploader-uploadedfiles>
        <e-uploader-uploadedfiles name="Movies" Size=12000 type=".pdf"></e-uploader-uploadedfiles>
        <e-uploader-uploadedfiles name="Study materials" size="500000" type=".docx"></e-uploader-uploadedfiles>
    </e-uploader-files>
</ejs-uploader>
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 ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Output be like the below.

uploader

Adding additional HTTP headers with upload action

The Uploader control allows you to add the additional headers with save and remove action requests using the uploading and removing events, which helps to send validation token on file upload. Access the current request and set the request header within these events.

The following code block shows how to add the additional headers with save and remove action request.

  <ejs-uploader id="UploadFiles" dropArea=".control-fluid" uploading="addHeaders" removing = "addHeaders" asyncSettings="@asyncSettings"></ejs-uploader>
    function addHeaders(args) {
        args.currentRequest.setRequestHeader('custom-header', 'Syncfusion');
    }

You can also explore ASP.NET Core File Upload feature tour page for its groundbreaking features. You can also explore our ASP.NET Core File Upload example to understand how to browse the files which you want to upload to the server.

See Also