【问题标题】:JQUERY - Drag & Drop file input replaces previous added filesJQUERY - 拖放文件输入替换以前添加的文件
【发布时间】:2021-12-09 13:49:10
【问题描述】:

我正在制作用户生成的音乐播放列表。用户使用按钮删除文件/添加文件。

但是,只要删除/添加了更多文件,就会替换之前添加的文件。

如何修改代码以将文件附加到之前添加的文件中?

PS: 我已经使用 jquery 来构建应用程序。我使用了 jquery,因为我想使用音频持续时间(以查找播放列表的总播放时间等),而使用 vanillaJS 实现这一点有点困难。

var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};

var objectUrl;

// Function
$(function() {
  var ooleft = dropZone.offset().left;
  var ooright = dropZone.outerWidth() + ooleft;
  var ootop = dropZone.offset().top;
  var oobottom = dropZone.outerHeight() + ootop;

  document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
    e.preventDefault();
    e.stopPropagation();
    dropZone.addClass(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
      inputFile.offset({
        top: y - 15,
        left: x - 100
      });
    } else {
      inputFile.offset({
        top: -400,
        left: -400
      });
    }

  }, true);

  if (buttonId != "") {
    var clickZone = $("#" + buttonId);

    var oleft = clickZone.offset().left;
    var oright = clickZone.outerWidth() + oleft;
    var otop = clickZone.offset().top;
    var obottom = clickZone.outerHeight() + otop;

    $("#" + buttonId).mousemove(function(e) {
      var x = e.pageX;
      var y = e.pageY;
      if (!(x < oleft || x > oright || y < otop || y > obottom)) {
        inputFile.offset({
          top: y - 15,
          left: x - 160
        });
      } else {
        inputFile.offset({
          top: -400,
          left: -400
        });
      }
    });
  }

  document.getElementById(dropZoneId).addEventListener("drop", function(e) {
    $("#" + dropZoneId).removeClass(mouseOverClass);
  }, true);

  // FILE
  inputFile.on('change', function(e) {
    finalFiles = {};
    $('#filename').html("");
    var fileNum = this.files.length,
      initial = 0,
      counter = 0;

    $.each(this.files, function(idx, elm) {
      finalFiles[idx] = elm;
    });

    for (initial; initial < fileNum; initial++) {
      counter = counter + 1;

      // Object URL
      var file = e.currentTarget.files[initial];
      objectUrl = URL.createObjectURL(file);
      $("#filename").prop("src", objectUrl);
      //console.log('Object URL: ', objectUrl);
      //console.log('FILE: ', file);
      // Object URL End



      //$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + '&nbsp;&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
      //$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + '&nbsp;&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');

      $('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file-audio-o"></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + '</strong></span> ' + '<audio controls controlsList="nodownload noplaybackrate" preload="auto" id="audioFiles" >' + '<source src="' + objectUrl + '" type="audio/mpeg" />' + '</audio>' + '<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span>&nbsp;' + this.files[initial].name + '</div>');
      //$('#filename').append('<div class="playlist draggable" id="file_' + initial + '">' + '<audio controls id="audioFiles" >' + '<source src="' + objectUrl + '/' + this.files[initial].name + '" type="audio/mpeg" />' + '</audio>' + '</div>');

      console.log('NAME: ', this.files[initial].name);
      //console.log('INITIAL: ', this.files[initial]);

      // Audio Duration
      var Duration;
      $(audioFiles).on("canplay", function() {
        console.log('THIS DURATION: ', this.duration);
        Duration = this.duration;
      });
      // Audio Duration End

    }

    // Total File Count
    var count = $('#filename').children().length;
    console.log('Number of files: ', count);

    $('#totalFiles').css("display", "initial");
    $('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
    // End Total File Count



  });
})

function removeLine(obj) {
  inputFile.val('');
  var jqObj = $(obj);
  var container = jqObj.closest('div');
  var index = container.attr("id").split('_')[1];
  container.remove();

  delete finalFiles[index];
  //console.log(finalFiles);
  URL.revokeObjectURL(objectUrl);

  // Total Files
  var count = $('#filename').children().length;
  console.log('Number of files: ', count);
  $('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');

  if (count == 0) {
    $('#totalFiles').css("display", "none");
  } else {}

}


// Draggable Items
$(function() {
  $('.draggable, .droppable').sortable({
    connectWith: '.playlists'
  });
});
@import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  overflow-y: visible;
  font-family: 'Source Code Pro', monospace;
}

.dropper {
  padding: 10px;
}

#drop-zone {
  width: 100%;
  min-height: 150px;
  border: 3px dashed rgba(0, 0, 0, .3);
  border-radius: 5px;
  font-family: 'Source Code Pro', monospace;
  text-align: center;
  position: relative;
  font-size: 20px;
  color: #7E7E7E;
}

#drop-zone input {
  position: absolute;
  cursor: pointer;
  left: 0px;
  top: 0px;
  opacity: 0;
}


/*Important*/

#drop-zone.mouse-over {
  border: 3px dashed rgba(0, 0, 0, .3);
  color: #7E7E7E;
}


/*If you dont want the button*/

#clickHere {
  display: inline-block;
  cursor: pointer;
  color: white;
  font-size: 1rem;
  width: 200px;
  border-radius: 0px;
  background-color: #000000;
  padding: 10px;
}

#clickHere:hover {
  background-color: #376199;
}

.uploadedFiles {
  padding: 0;
  margin: 10px 50px;
}

#filename {
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 10px;
  font-size: 14px;
  line-height: 1.5em;
  border: 1px solid;
  min-height: 200px;
  max-height: 400px;
  overflow-y: scroll;
  color: #240aff;
}

#filename span {
  font-size: 1.5rem;
  line-height: 1.2rem;
  height: 1.5rem;
  width: 1.5rem;
}


/* File Info */

#totalFiles {
  border: 1px solid #06a7e5;
  padding: 5px;
  display: none;
}

.file-preview {
  background: rgb(99, 8, 8);
  border: 5px solid #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  font-size: 14px;
  margin-top: 5px;
}

.closeBtn {
  color: black;
  display: inline-block;
  vertical-align: -20%!important;
}

.closeBtn:hover {
  color: red;
  display: inline-block;
  cursor: pointer;
}

.playlist {
  border: 1px solid black;
  padding: 10px;
  margin: 5px;
  background: #e9eaf9;
}

.playlist:hover {
  cursor: move;
}


/* AUDIO CONTROLS */

#audioFiles {
  vertical-align: middle;
  margin: 0px 10px 0px 0px;
}

audio {
  /*
    filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
    */
  width: 25%;
  height: 35px;
}

audio::-webkit-media-controls-enclosure {
  border-radius: 5px;
  background-color: #cfcfcf;
}
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Upload & Draggable</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon">

  <link rel="stylesheet" href="./style.css">

  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js" integrity="sha256-xH4q8N0pEzrZMaRmd7gQVcTZiFei+HfRTBPJ1OGXC0k=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />


</head>

<body>

  <div class="dropper">
    <div id="drop-zone">
      <p>Drop files here</p>
      <div id="clickHere">or click here <i class="fa fa-upload"></i>
        <input type="file" name="file" id="file" multiple accept="audio/*" />
      </div>
    </div>
  </div>

  <div class="uploadedFiles">
    <p>Uploaded Files are Draggable.&nbsp;<span id="totalFiles"></span></p>

    <div id="filename" class="playlists droppable"></div>
  </div>

  <!--
    <audio id="audio2"></audio>
    
    <p>
        <label>File Size:</label>
        <span id="filesize"></span>
        <input type="hidden" id="size" name="size" value="" />
    </p>
    
    <p>
        <label>Total Duration:</label>
        <span id="duration"></span>
        <input type="hidden" id="timelength" name="time" value="" />       
    </p>
    -->

  <script src="./script.js" async defer></script>
</body>

</html>

【问题讨论】:

    标签: javascript jquery html5-audio


    【解决方案1】:

    当我删除以下 jquery 代码行时效果很好:

    $('#filename').html("");
    

    【讨论】:

      猜你喜欢
      • 2014-04-06
      • 2015-10-28
      • 2017-09-08
      • 1970-01-01
      • 2015-08-09
      • 2017-07-09
      • 2014-02-05
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多