Saturday, August 10, 2019

Drag & drop file upload in ASP.NET MVC

This is a very simple article today I am going to explain but Drag & drop file uploading is a very common requirement for any web application nowadays.  Drag and drop is a great HTML5 feature. So let Start implementing drag & drop file uploading in ASP.NET MVC application.

In this tutorial, we will see how to implement this using the FileDrop jQuery plugin.  jQuery FileDrop uses the HTML5 File API to allow users to drag multiple files from desktop to the browser, uploading each file to a user-specified URL.
Ok, let's start importing Drag & drop file upload in ASP.NET MVC.


Follow the following steps in order to implement "Drag & drop file upload in ASP.NET MVC".

Here In this article, I have used Visual Studio 2015

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Enter enter application name > select your project location > and then click on add button > It will brings up a new dialog window for select template > here I will select Empty template > checked  MVC checkbox from Add folder and core referances for: > and then click on ok button.

Step-2: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.
Here I have created a controller "HomeController"
Now we will add a view for Index action (which is already added in the home controller) where we will implement drag & drop file upload. 

Step-3: Add view for Index action.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select "Empty" under Template dropdown > Check use a layout page  > > Add.

    HTML Code

    1. @{
    2. ViewBag.Title = "Index";
    3. }
    4.  
    5. <h2>Drag & Drop file upload </h2>
    6. <div id="dropArea">
    7. Drop your files here
    8. </div>
    9. <h4>Uploaded files : </h4>
    10. <ul class="list-group" id="uploadList">
    11.  
    12. </ul>
    13.  
    14. <style>
    15. #dropArea{
    16. background:#b5b5b5;
    17. border:black dashed 1px;
    18. height:50px;
    19. text-align:center;
    20. color:#fff;
    21. padding-top:12px;
    22. }
    23. .active-drop{
    24. background:#77bafa !important;
    25. border:solid 2px blue !important;
    26. opacity:.5;
    27. color:black !important;
    28. }
    29. </style>
    30.  
    31. @section Scripts{
    32. <script src="~/Scripts/jquery.filedrop.js"></script>
    33. <script type="text/javascript">
    34. $(function () {
    35. $('#dropArea').filedrop({
    36. url: '@Url.Action("UploadFiles")',
    37. allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif'],
    38. allowedfileextensions: ['.jpg', '.jpeg', '.png', '.gif'],
    39. paramname: 'files',
    40. maxfiles: 5,
    41. maxfilesize: 5, // in MB
    42. dragOver: function () {
    43. $('#dropArea').addClass('active-drop');
    44. },
    45. dragLeave: function () {
    46. $('#dropArea').removeClass('active-drop');
    47. },
    48. drop: function () {
    49. $('#dropArea').removeClass('active-drop');
    50. },
    51. afterAll: function (e) {
    52. $('#dropArea').html('file(s) uploaded successfully');
    53. },
    54. uploadFinished: function (i, file, response, time) {
    55. $('#uploadList').append('<li class="list-group-item">'+file.name+'</li>')
    56. }
    57. })
    58. })
    59. </script>
    60. }
    Step-4: Update _Layout.cshtml page.

    Here we will add a section for render script from another view. See the yellow marked lines. 
       

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8" />
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>@ViewBag.Title - My ASP.NET Application</title>
    7. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    8. <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    9. <script src="~/Scripts/modernizr-2.6.2.js"></script>
    10. </head>
    11. <body>
    12. <div class="navbar navbar-inverse navbar-fixed-top">
    13. <div class="container">
    14. <div class="navbar-header">
    15. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    16. <span class="icon-bar"></span>
    17. <span class="icon-bar"></span>
    18. <span class="icon-bar"></span>
    19. </button>
    20. @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    21. </div>
    22. <div class="navbar-collapse collapse">
    23. <ul class="nav navbar-nav">
    24. </ul>
    25. </div>
    26. </div>
    27. </div>
    28.  
    29. <div class="container body-content">
    30. @RenderBody()
    31. <hr />
    32. <footer>
    33. <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    34. </footer>
    35. </div>
    36.  
    37. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    38. <script src="~/Scripts/bootstrap.min.js"></script>
    39. @RenderSection("Scripts", required:false)
    40. </body>
    41. </html>

    Step-5: Add jquery.filedrop.js from nuget.

    Here in this article, we have used jquery.filedrop.js. We will add this js library into our application from NuGet.

    Go to solution explorer > Right click on project name > Manage NuGet Packages... > Search with this keyword "jquery-filedrop" > Select and click Install button.

    Step-6: Add an another Action in HomeController.

    Add an another MVC action in the HomeController for upload file on the server.
    1. [HttpPost]
    2. public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
    3. {
    4. foreach (var file in files)
    5. {
    6. string filePath = Guid.NewGuid() + Path.GetExtension(file.FileName);
    7. file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), filePath));
    8. //Here you can write code for save this information in your database if you want
    9. }
    10. return Json("file uploaded successfully");
    11. }

    Step-7: Add a folder in your application

    Now we will add a folder into our application where we will store uploaded files.

    Go to Solution Explorer > Right Click on the project name > Add > New Folder. 
    I have renamed the folder as "UploadedFiles".


    Step-8: Update web.config file.

    This is required only when you want to allow more than 4MB file size.  Here I have allowed 5 MB (5120 KB).

    Step-9: Run Application.

    We have done all the steps. Now it's time to run the application. 

    No comments:

    Post a Comment

    How to register multiple implementations of the same interface in Asp.Net Core?

     Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...