• We just launched and are currently in beta. Join us as we build and grow the community.

Drag and Drop - Uploading Multiple Files using Pure JavaScript Tutorial

mmammamma0

PPC Campaign Architect
M Rep
0
0
0
Rep
0
M Vouches
0
0
0
Vouches
0
Posts
151
Likes
171
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
In this tutorial, you will learn how to create or implement a Drag and Drop File Uploading using Pure JavaScript. This tutorial mainly aims to provide IT/CS Students and new programmers with a reference to handle file uploads on both the client and server sides. Here, the step-by-step tutorial for achieving the main objective is provided with snippets for better understanding. A sample web application source code zip file that demonstrates the tutorial's objective is also provided and is free to download.

What is Drag-and-Drop File Uploading?

Drag-and-Drop File Uploading is a process of handling file uploads on the client side. It allows the end user of a certain system or platform to simply drag the files they desire to upload and drop to a certain container or file drop zone on the platform page.

How to Create a Drag-and-Drop File using JavaScript?

Drag-and-Drop functionality can be achieved using the JavaScript EventListeners. Here are the following event listeners that can be used to achieve the said functionality:

  • ondragover
    • This event listener enables you to create a process, functions, or manipulations that will be triggered when the dragged file hovers over the drop zone field.
  • ondragleave
    • This event listener enables you to create a process, functions, or manipulations that will be triggered when the dragged file leaves the drop zone field.
  • ondrop
    • This event listener enables you to create a process, functions, or manipulations that will be triggered when the dragged file has been dropped at the drop zone field.

Sample Syntax

Here's a sample snippet that demonstrates how to use the said event listeners.

  1. document.getElementById

    (

    'drop-zone'

    )

    .ondragover

    =

    function

    (

    event)
  2. {
  3. // Add something here
  4. }
  5. document.getElementById

    (

    'drop-zone'

    )

    .ondragleave

    =

    function

    (

    event)
  6. {
  7. // Add something here
  8. }
  9. document.getElementById

    (

    'drop-zone'

    )

    .ondrop

    =

    function

    (

    event)
  10. {
  11. // Add something here
  12. }

Example

Here are the source code snippets of simple web applications that demonstrate the Drag-and-Drop Multiple File Upload with a progress bar using the 3 event listeners mentioned above. The application allows the end-users to upload multiple files by simply drag-and-drop the files on the application files drop zone. The uploading process to the server will be executed using the JS HTTP Request and PHP Script.

Interface

Here's the snippet of the application page interface. The file is a combined PHP and HTML script for displaying the file drop zone and uploaded files. I used Bootstrap v5 and Fontawesome Icons for the design of the interface which is loaded using CDNs. Save the file as index.php

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    JS Drag and Drop - Upload Multiple File</

    title

    >
  8. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"

    integrity=

    "sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    /

    >
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"

    crossorigin=

    "anonymous"

    >
  10. <link

    rel

    =

    "stylesheet"

    href

    =

    "style.css"

    >

  11. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js"

    integrity=

    "sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >
  12. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    integrity=

    "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"

    crossorigin=

    "anonymous"

    ></

    script

    >
  13. </

    head

    >
  14. <body

    >
  15. <nav class

    =

    "navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"

    >
  16. <div

    class

    =

    "container"

    >
  17. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    JS Drag and Drop - Upload Multiple File</

    a

    >
  18. <div

    >
  19. <a

    href

    =

    "https://sourcecodester.com"

    class

    =

    "text-light fw-bolder h6 text-decoration-none"

    target

    =

    "_blank"

    >

    SourceCodester</

    a

    >
  20. </

    div

    >
  21. </

    div

    >
  22. </

    nav>
  23. <div

    class

    =

    "container-fluid px-5 my-3"

    >
  24. <div

    class

    =

    "col-lg-6 col-md-8 col-sm-12 mx-auto"

    >
  25. <div

    class

    =

    "card rounded-0"

    >
  26. <div

    class

    =

    "card-body rounded-0"

    >
  27. <div

    class

    =

    "container-fluid"

    >
  28. <div

    id

    =

    "msg"

    ></

    div

    >
  29. <!-- Drag and Drop Field -->
  30. <div

    id

    =

    "dd-field"

    >
  31. <h3

    class

    =

    "text-muted"

    >

    Drag and Drop Files Here</

    h3

    >
  32. </

    div

    >
  33. <div

    class

    =

    "my-2"

    >
  34. <div

    class

    =

    "progress"

    id

    =

    "upload-progress-holder"

    style

    =

    "display:none"

    >
  35. <div

    class

    =

    "progress-bar"

    id

    =

    "upload-progress"

    role=

    "progressbar"

    aria-label

    =

    "Example with label"

    style

    =

    "width: 0%;"

    aria-valuenow=

    "0"

    aria-valuemin=

    "0"

    aria-valuemax=

    "100"

    >

    0%</

    div

    >
  36. </

    div

    >
  37. </

    div

    >
  38. <div

    id

    =

    "upload-field"

    >
  39. <?php
  40. if(

    is_dir(

    "uploads/"

    )

    )

    :
  41. $scandr =

    scandir(

    "uploads/"

    )

    ;
  42. foreach(

    $scandr as $file)

    {
  43. if(

    in_array(

    $file, [

    "."

    , ".."

    ]

    )

    )
  44. continue;
  45. $type =

    mime_content_type(

    "uploads/"

    .$file)

    ;
  46. ?>
  47. <div

    class

    =

    "uploaded-file-item"

    >
  48. <?php if(

    strstr(

    $type, "image/"

    )

    )

    : ?>
  49. <a

    href

    =

    "uploads/<?= $file ?>

    " class="image-holder" target="_blank">
  50. <img

    src

    =

    "uploads/<?= $file ?>

    " alt="">
  51. </

    a

    >
  52. <?php else: ?>
  53. <a

    href

    =

    "uploads/<?= $file ?>

    " class="icon-holder" target="_blank">
  54. <i

    class

    =

    "fa-solid fa-file"

    ></

    i

    >
  55. </

    a

    >
  56. <?php endif; ?>
  57. <div

    class

    =

    "text-center"

    ><?=

    $file ?></

    div

    >
  58. </

    div

    >
  59. <?php }

    ?>
  60. <?php endif; ?>
  61. </

    div

    >
  62. </

    div

    >
  63. </

    div

    >
  64. </

    div

    >
  65. </

    div

    >
  66. </

    div

    >
  67. <script

    src

    =

    "upload-file-dd.js"

    ></

    script

    >
  68. </

    body

    >
  69. </

    html

    >

Custom Style

Here is the snippet of the custom cascading stylesheet or CSS for some of the designs of the interface. Save the file style.css.

  1. html,

    body{
  2. min-height

    :

    100%

    ;
  3. width

    :

    100%

    ;
  4. }
  5. #dd-field

    {
  6. width

    :

    100%

    ;
  7. height

    :

    15vh

    ;
  8. border

    :

    2px

    dashed

    #b5b5b5

    ;
  9. border-radius

    :

    15px

    ;
  10. overflow

    :

    auto

    ;
  11. padding

    :

    1em

    ;
  12. display

    :

    flex;
  13. color

    :

    #b5b5b5

    ;
  14. font-size

    :

    1.5em

    ;
  15. align-items

    :

    center

    ;
  16. justify-content

    :

    center

    ;
  17. }
  18. #upload-field

    {
  19. width

    :

    100%

    ;
  20. height

    :

    45vh

    ;
  21. border

    :

    2px

    solid

    #b5b5b5

    ;
  22. border-radius

    :

    15px

    ;
  23. overflow

    :

    auto

    ;
  24. padding

    :

    1em

    ;
  25. display

    :

    flex;
  26. flex-wrap

    :

    wrap;
  27. }
  28. #upload-field

    :

    empty

    {
  29. align-items

    :

    center

    ;
  30. justify-content

    :

    center

    ;
  31. }
  32. #upload-field

    :

    empty

    :

    after

    {
  33. content

    :

    "Uploads Directory is empty"

    ;
  34. color

    :

    #b5b5b5

    ;
  35. font-size

    :

    1em

    ;
  36. }
  37. .uploaded-file-item

    {
  38. width

    :

    30%

    ;
  39. margin

    :

    1.5%

    ;
  40. }
  41. .image-holder

    ,

    .icon-holder

    {
  42. width

    :

    100%

    ;
  43. height

    :

    10vh

    !important;
  44. background-color

    :

    black

    ;
  45. border

    :

    #b5b5b5

    ;
  46. border-radius

    :

    5px

    ;
  47. display

    :

    block

    ;
  48. }
  49. .icon-holder{
  50. color

    :

    #fff

    ;
  51. font-size

    :

    3em

    ;
  52. text-align

    :

    center

    ;
  53. }
  54. .image-holder>

    img {
  55. width

    :

    100%

    ;
  56. height

    :

    100%

    ;
  57. object-fit

    :

    scale-down;
  58. object-position

    :

    center

    center

    ;
  59. }

PHP API

The following snippet is a PHP script that uploads the files to the server. The script contains a simple logic for managing the files with duplicate filenames. This API will be executed by the JS HTTP Request. Save the file as upload_files.php

  1. <?php
  2. // Upload Directory
  3. $dir

    =

    "uploads/"

    ;

  4. /**
  5. * Check and Create Uploads Directory If not Existing Yet
  6. */
  7. if

    (

    !

    is_dir

    (

    $dir

    )

    )
  8. mkdir

    (

    $dir

    )

    ;

  9. if

    (

    isset

    (

    $_FILES

    [

    'files'

    ]

    )

    &&

    count

    (

    $_FILES

    [

    'files'

    ]

    [

    'tmp_name'

    ]

    )

    >

    0

    )

    {
  10. $files

    =

    $_FILES

    [

    'files'

    ]

    ;
  11. $total_files

    =

    count

    (

    $_FILES

    [

    'files'

    ]

    [

    'tmp_name'

    ]

    )

    ;
  12. $uploaded_files

    =

    [

    ]

    ;
  13. $uploaded

    =

    0

    ;
  14. foreach

    (

    $files

    [

    'tmp_name'

    ]

    as

    $k

    =>

    $file

    )

    {


  15. if

    (

    !

    empty

    (

    $file

    )

    )

    {

  16. // Get the File Path Info
  17. $filepath_part

    =

    pathinfo

    (

    $files

    [

    'name'

    ]

    [

    $k

    ]

    )

    ;
  18. // Get the filename
  19. $filename

    =

    $filepath_part

    [

    'filename'

    ]

    ;
  20. // Get the extension
  21. $extension

    =

    $filepath_part

    [

    'extension'

    ]

    ;
  22. // File Full Name w/ Extension
  23. $filefullname

    =

    $filename

    .

    "."

    .

    $extension

    ;
  24. // Content Mime Type
  25. $mime_type

    =

    mime_content_type

    (

    $file

    )

    ;

  26. // print($mime_type."<br>");
  27. // continue;

  28. /**
  29. * Check and Rename Filename if file already exists.
  30. */

  31. // temporary filename for checking duplicate
  32. $tmp_name

    =

    $filefullname

    ;

  33. //Duplicate Iteration Number
  34. $i

    =

    0

    ;
  35. while

    (

    true

    )

    {
  36. if

    (

    $i

    >

    0

    )
  37. $tmp_name

    =

    $filename

    .

    " ($i

    )"

    .

    "."

    .

    $extension

    ;

  38. if

    (

    is_file

    (

    $dir

    .

    $tmp_name

    )

    )

    {
  39. $i

    ++;
  40. }

    else

    {
  41. $filefullname

    =

    $tmp_name

    ;
  42. break

    ;
  43. }
  44. }

  45. /**
  46. * Move file to uploads directory
  47. */
  48. $upload

    =

    move_uploaded_file

    (

    $file

    ,

    $dir

    .

    $filefullname

    )

    ;
  49. if

    (

    $upload

    )

    {
  50. $uploaded_files

    [

    ]

    =

    [

    "filename"

    =>

    $filefullname

    ,

    "type"

    =>

    $mime_type

    ]

    ;
  51. $uploaded

    ++;
  52. }
  53. }
  54. }
  55. if

    (

    $uploaded

    ==

    $total_files

    )

    {
  56. echo

    json_encode

    (

    [
  57. "status"

    =>

    'success'

    ,
  58. "msg"

    =>

    'File has been uploaded successfully.'

    ,
  59. "uploads"

    =>

    $uploaded_files
  60. ]

    )

    ;
  61. }

    elseif

    (

    $uploaded

    >

    0

    &&

    $uploaded

    <

    $total_files

    )

    {
  62. echo

    json_encode

    (

    [
  63. "status"

    =>

    'success'

    ,
  64. "msg"

    =>

    'Some Files has been uploaded successfully and some has failed due to some reason.'

    ,
  65. "uploads"

    =>

    $uploaded_files
  66. ]

    )

    ;
  67. }

    else

    {
  68. echo

    json_encode

    (

    [
  69. "status"

    =>

    'error'

    ,
  70. "msg"

    =>

    'Files has failed due to some reason.'
  71. ]

    )

    ;
  72. }
  73. }

    else

    {
  74. echo

    json_encode

    (

    [
  75. "status"

    =>

    'error'

    ,
  76. "msg"

    =>

    'No files sent on this request.'
  77. ]

    )

    ;
  78. }

JavaScript

Here is the JavaScript snippet that contains the main object of this tutorial. It has a script that implements the Drag-and-Drop functionality of the system and triggers to upload of the dropped files. Save the file as upload-file-dd.js.

  1. /**
  2. * Check if Upload Field is empty
  3. */
  4. window.onload

    =

    function

    (

    )

    {
  5. if

    (

    document.getElementById

    (

    'upload-field'

    )

    .innerText

    ==

    ""

    )

    {
  6. document.getElementById

    (

    'upload-field'

    )

    .innerHTML

    =

    ""
  7. }
  8. }

  9. /**
  10. * Drag and Drop Field Drag Over CSS Change
  11. */
  12. document.getElementById

    (

    'dd-field'

    )

    .ondragover

    =

    function

    (

    event)
  13. {
  14. this

    .style

    .borderColor

    =

    '#000'

    ;
  15. return

    false

    ;
  16. }

  17. /**
  18. * Drag and Drop Field Drag Leave CSS Change
  19. */
  20. document.getElementById

    (

    'dd-field'

    )

    .ondragleave

    =

    function

    (

    event)
  21. {
  22. this

    .style

    .borderColor

    =

    '#b5b5b5'

    ;
  23. return

    false

    ;
  24. }


  25. /**
  26. * Drag and Drop Field Dropped Files
  27. * Process and Upload Files
  28. */
  29. document.getElementById

    (

    'dd-field'

    )

    .ondrop

    =

    function

    (

    event)
  30. {
  31. event.preventDefault

    (

    )

    ;
  32. document.getElementById

    (

    'msg'

    )

    .innerHTML

    =

    ""

    ;

  33. this

    .style

    .borderColor

    =

    '#429ebe'

    ;
  34. var

    form_data =

    new

    FormData(

    )

    ;


  35. var

    error =

    ''

    ;

  36. var

    drop_files =

    event.dataTransfer

    .files

    ;

  37. // Allowed Files to Upload
  38. var

    valid_files =

    [

    'image/jpeg'

    ,

    'image/png'

    ,

    'video/mp4'

    ,

    'application/gzip'

    ,

    'image/gif'

    ,

    'text/html'

    ,

    'application/json'

    ,

    'application/pdf'

    ,

    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

    ,

    'application/msword'

    ,

    'text/csv'

    ,

    'text/plain'

    ]

    ;

  39. for

    (

    var

    count =

    0

    ;

    count <

    drop_files.length

    ;

    count++

    )
  40. {
  41. if

    (

    !

    valid_files.includes

    (

    drop_files[

    count]

    .type

    )

    )
  42. {
  43. // In File type is not allowed
  44. error +=

    `<

    div class

    =

    "alert alert-danger rounded-0 mb-3"

    ><

    b>

    ${

    drop_files[

    count]

    .name

    }

    's</b> File Type is not valid.</div>`;
  45. }
  46. else
  47. {
  48. form_data.append("files[]", drop_files[count]);
  49. }

  50. }

  51. if(error != '

    ')
  52. {
  53. // Return Error Message

  54. document.getElementById('

    msg').innerHTML = error;
  55. document.getElementById('

    dd-

    field').style.borderColor = '

    #b5b5b5';
  56. }
  57. else
  58. {
  59. // Display Progress Bar
  60. document.getElementById('

    upload-

    progress-

    holder').style.display = '

    block';


  61. /**
  62. * Upload files
  63. */

  64. var httpRequest = new XMLHttpRequest();
  65. httpRequest.open("post", "upload_files.php");
  66. httpRequest.responseType = "json"
  67. httpRequest.upload.addEventListener('

    progress', function(event){
  68. /**
  69. * Update Progress Bar while Upload is inProgress
  70. */
  71. var percent_completed = Math.round((event.loaded / event.total) * 100);

  72. document.getElementById('

    upload-

    progress').style.width = percent_completed + '

    %

    ';

  73. document.getElementById('

    upload-

    progress').innerHTML = percent_completed + '

    %

    completed';

  74. });
  75. httpRequest.addEventListener('

    load', function(event){
  76. // Upload Response
  77. response = httpRequest.response
  78. // console.log(response)
  79. if(!!response.status){
  80. if(response.status == '

    success'){
  81. // IF File Upload is successfull
  82. if(!!response.msg)
  83. document.getElementById('

    msg').innerHTML = `<div class="alert alert-success rounded-0 mb-3">${response.msg}</div>`;
  84. if(!!response.uploads){
  85. /**
  86. * Add Newly Uploaded files to upload field
  87. */
  88. Object.keys(response.uploads).map(k => {
  89. var fname = response.uploads[k].filename
  90. var type = response.uploads[k].type

  91. var el = document.createElement("div")
  92. el.classList.add("uploaded-file-item")
  93. if(type.includes("image/") === true){
  94. el.innerHTML = `
  95. <a href="uploads/${fname}" class="image-holder" target="_blank">
  96. <img src="uploads/${fname}">
  97. </a>
  98. <div class="text-center">${fname}</div>
  99. `
  100. }else{
  101. el.innerHTML = `
  102. <a href="uploads/${fname}" class="icon-holder" target="_blank">
  103. <i class="fa-solid fa-file"></i>
  104. </a>
  105. <div class="text-center">${fname}</div>
  106. `
  107. }
  108. document.getElementById('

    upload-

    field').innerHTML = el.outerHTML + document.getElementById('

    upload-

    field').innerHTML
  109. document.getElementById('

    upload-

    field').scrollTop = 0
  110. })
  111. }
  112. }else if(response.status == '

    error'){
  113. if(!!response.msg)
  114. document.getElementById('

    msg').innerHTML = `<div class="alert alert-danger rounded-0 mb-3">${response.msg}</div>`;
  115. }else{
  116. document.getElementById('

    msg').innerHTML = `<div class="alert alert-danger rounded-0 mb-3">An error occurred while uploading the files.</div>`;
  117. }
  118. }

  119. document.getElementById('

    dd-

    field').style.borderColor = '

    #b5b5b5';

  120. });

  121. httpRequest.send(form_data);
  122. }
  123. }


That's it! You can now test the application source code on your end. The upload directory will be automatically created upon uploading files for the first time using the application. I also provided the application's complete source code zip file with this article and it is free to download. You can download it by clicking the Download Button located below this article.

Snapshots

Main Interface

Successful File Upload

There you go! That's the end of this tutorial. I hope this Uploading Drag-and-Drop Multiple Files using JavaScript Tutorial helps you with what you are looking for and will be useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,341

323,350

Top