In this article, we are going to learn how to upload a file just drag and dropping in the zone in asp.net core in simple steps

We are going to use one of the popular JavaScript drag-and-drop libraries for file upload in this article.

Table of Contents

  • Creating Project
  • Project structure
  • Adding Controller and View
  • Introduction to Dropzone.js JavaScript Library
  • Links to Download Scripts & CDN Links
  • UploadFiles View
  • Code Snippet of UploadFiles View
  • The View of Dropzone File Upload
  • Script of DropZone
  • Storing Posted Files in a Folder
  • Let’s Run the application
  • Debug view of uploaded files
  • Uploaded files which are Stored in a folder
  • Conclusion
  • Download Source Code

    Let’s Get Started

    Creating Project

    We are going to create a new application, as shown below.

    Next, we are going to set Project Name DemoDropZone and location. In the last part, we will choose the .Net Core framework and ASP.NET Core Version 6.0 as the framework for the application and a few advanced settings such as configuring HTTPS and enabling docker; we are not going to enable docker settings for this project.

    Now finally, click on create button to create a project.

    Project structure

    The project structure is generated according to the configuration.

    After creating the project next, we are going to Controller and View.

    Adding Controller and View

      [HttpGet]
      public IActionResult UploadFiles()
      {
          return View();
      }

    Introduction to Dropzone.js JavaScript Library

    Dropzone.js is one of the most popular drag-and-drop JavaScript libraries. It is free, fully open source, and makes it easy for you to handle dropped files on your website.

    After Introduction now let us Use it in a real scenario for doing that, we have to download the script and .css of Dropzone js.

    Links to Download Scripts

    https://docs.dropzone.dev/getting-started/installation/stand-alone

    CDN Links

    If you want to use CDN then you can directly use the link given below.

    <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
    
    <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
    

    After downloading the files I added them to the js folder which is inside the wwwroot folder.

    Next, we are going to add Script and CSS on View and Design view for using Dropzone.

    UploadFiles View

    In this part, we have added script and CSS reference on View.

    @section Scripts{
    <link href="~/js/dropzone/dropzone.min.css" rel="stylesheet" />
    <script src="~/js/dropzone/dropzone.min.js"></script>
    }

    The added Form tag is encoded as “multipart/form-data” and also added div tag is above the form tag and assigned id as “demo-upload”.

    Code Snippet of UploadFiles View

    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Files Uploads</h3>
            </div>
            <div class="card-body register-card-body">
                <div class="form-row">
                    <div class="col-md-12" id="dropzone">
                        <form asp-controller="DemoUpload" autocomplete="off" asp-antiforgery="true" class="dropzone"
                              id="demo-upload" enctype="multipart/form-data" asp-action="UploadFiles" method="post">
                            <div class="text-danger" asp-validation-summary="ModelOnly"></div>
                            <div class="form-row">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <button type="button" id="btnupload" class="btn btn-success">Upload Files</button>
          
                <a class="btn btn-danger" asp-controller="DemoUpload" asp-action="UploadFiles">Clear</a>
            </div>
        </div>
    </div> 
    
    @section Scripts{
    <link href="~/js/dropzone/dropzone.min.css" rel="stylesheet" />
    <script src="~/js/dropzone/dropzone.min.js"></script>
    }

    The View of Dropzone File Upload

    Script of DropZone

    In this Dropzone, we have various options to configure it such as Maxfilesize, MaxFiles, and Accepted Files.

    <script>
        Dropzone.autoDiscover = false;
        $(function () {
            var dz = null;
            $("#demo-upload").dropzone({
                autoProcessQueue: false,
                paramName: "File Upload",
                maxFilesize: 5, //mb
                maxThumbnailFilesize: 1, //mb
                maxFiles: 5,
                parallelUploads: 5,
                acceptedFiles: ".jpeg,.png,.jpg",
                uploadMultiple: true,
                addRemoveLinks: true,
         
                init: function () 
                {
                    dz = this;
                    $("#btnupload").click(function () 
                    {
                        dz.processQueue();
                        $(this).attr("disabled", "disabled");
                    });
                },
                success: function (file) 
                {
                    var preview = $(file.previewElement);
                    preview.addClass("dz-success text-success");
                    setTimeout(function () 
                    {
                        dz.removeFile(file);
                    
                    }, 2000);
    
                },
                queuecomplete: function () 
                {
                    alert('Files Uploaded Successfully!');
                },
                dictDefaultMessage: "You can drag and drop your images here.",
                dictRemoveFile: "File Remove"
            });
     
        });
      
    </script>

    Now we have the script read next we need to call the action method where we can post these files and store them in the application folder.

    Storing Posted Files in a Folder

    In this part, we will get all Posted files in IFormCollection which we are going to iterate and store in the folder “UploadedFiles” which is located in the wwwroot folder of the application.

    [HttpPost]
            public async Task<IActionResult> UploadFiles(IFormFile filedata)
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Any())
                {
                    foreach (var file in files)
                    {
                        if (file.Length > 0)
                        {
                            //Getting FileName
                            var fileName = Path.GetFileName(file.FileName);
                            //Assigning Unique Filename (Guid)
                            var myUniqueFileName = Convert.ToString(Guid.NewGuid().ToString("N"));
                            //Getting file Extension
                            var fileExtension = Path.GetExtension(fileName);
                            // concatenating  FileName + FileExtension
                            var newFileName = String.Concat(myUniqueFileName, fileExtension);
                            await using var target = new MemoryStream();
                            await file.CopyToAsync(target);
                            var physicalPath = $"{new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "UploadedFiles")).Root}{$@"{fileName}"}";
                            string filePath = $"/UploadedFiles/{fileName}";
                            await using FileStream fs = System.IO.File.Create(physicalPath);
                            await file.CopyToAsync(fs);
                            fs.Flush();
                        }
                    }
    
                    return Json(new { status = true, Message = "Files Uploaded Successfully!" });
                }
    
                return View();
            }

    Let’s Run the application

    Debug view of uploaded files

    Uploaded files which are Stored in a folder

    Conclusion

    In this article, we have learned how to upload multiple files in ASP.NET CORE using DropZone.js in simple steps along with that we have also learned how to store it in an application folder.

    DropZone.js is a good library javascript for doing multiple files.

    Hope you Liked this Article Please share it if possible.

    Download Source Code

    https://github.com/saineshwar/DemoDropZone

    https://tutexchange.com/how-to-crop-and-resize-image-in-asp-net-core/

    By Saineshwar

    Microsoft MVP for Developer Technologies | C# Corner MVP | Code project MVP | Senior Technical Lead | Author | Speaker | Love .Net | Full Stack developer | Open source contributor.