Получение имени файла не определено - PullRequest
0 голосов
/ 02 ноября 2019

Я сделал цикл в своем jquery, чтобы получить список всех изображений, которые я перетащил. Я могу получить список изображений, но сейчас я пытаюсь поместить его в массив, чтобы я мог использовать его где-то еще в моем коде.

Вот мой код js

$(document).ready(function(){

    var dropZone = document.getElementById('drop-zone');

    var filename_list = [];
    dropZone.ondrop = function(e){
        e.preventDefault();

        for(x = 0; x < e.dataTransfer.files.length; x++)
        {
        //Gets the list of names from when I dragged images over
            var filename = e.dataTransfer.files[x].name

            //Pushing the list of filenames into an array
            filename_list.push(filename);
        }

    }

    //Trying to use the filename array outside of the loop
    console.log('filename - '+filename_list);

    dropZone.ondragover = function(e){
        return false;
    }

    dropZone.ondragleave = function(){
        return false;
    }
});

фрагмент здесь:

$(document).ready(function() {

  var dropZone = document.getElementById('drop-zone');

  var filename_list = [];
  dropZone.ondrop = function(e) {
    e.preventDefault();

    for (x = 0; x < e.dataTransfer.files.length; x++) {
      //Gets the list of names from when I dragged images over
      var filename = e.dataTransfer.files[x].name

      //Pushing the list of filenames into an array
      filename_list.push(filename);
    }

  }

  //Trying to use the filename array outside of the function
  console.log('filename - ' + filename_list);

  dropZone.ondragover = function(e) {
    return false;
  }

  dropZone.ondragleave = function() {
    return false;
  }
});
h1,
h2,
h3,
h4,
h5 {
  font-weight: 400;
}

.hidden {
  display: none;
}

.wrapper {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.upload-console {
  background: #fefefe;
  border: 2px solid #eee;
  padding: 20px;
}

.upload-console-header {
  padding: 0 0 20px 0;
  margin: 0;
  border-bottom: 2px solid #eee;
  font-weight: 600;
  margin-bottom: 20px;
}

.upload-console-drop {
  height: 200px;
  border: 2px dashed #ccc;
  line-height: 200px;
  color: #ccc;
  text-align: center;
  margin-bottom: 20px;
}

.upload-console-drop.drop {
  border-color: #222;
  color: #222;
}

.upload-console-body {
  margin-bottom: 20px;
}

.bar {
  width: 100%;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, .2);
  box-sizing: border-box;
  margin-bottom: 20px;
}

.bar-fill {
  height: 30px;
  display: block;
  background: cornflowerblue;
  width: 0;
  border-radius: 3px;
  -webkit-transition: width 0.8s ease;
  transition: width 0.8s ease;
}

.bar-fill-text {
  color: #fff;
  line-height: 30px;
  margin-left: 5px;
}

.upload-console-upload {
  border-bottom: 2px solid #ccc;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.upload-console-upload span {
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
  <div class="form-group">
    <label for="title">Title</label>
    <input type="text" class="form-control" name="title">
  </div>
  <div class="form-group">
    <label for="content">content</label>
    <textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
  </div>

  <input type="file" name="files[]" id="standard-upload-files" multiple>
  <input type="submit" value="Upload files" id="standard-upload">
  <div class="wrapper">
    <div class="upload-console">
      <h2 class="upload-console-header">
        Upload
      </h2>

      <div class="upload-console-body">
        <div class="upload-console-drop" id="drop-zone">
          just drag and drop files here
        </div>

        <div class="bar">
          <div class="bar-fill" id="bar-fill">
            <div class="bar-fill-text" id="bar-fill-text"></div>
          </div>
        </div>
        <div class="hidden" id="uploads-finished">
          <h3>Process files</h3>
          <div class="upload-console-upload">
            <a href="#">filename.jpg</a>
            <span>Success</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product" id="add_item">Save</button>
  </div>
</form>

Вот немного рабочая копия моего кода. CODEPEN

Ответы [ 2 ]

1 голос
/ 02 ноября 2019

вам нужно посмотреть на массив ПОСЛЕ того, как он будет заполнен для глобального (плохо, возможно, сделать это) или для события, которое я показываю обоим.

Также, если вы выберете один, я добавил это событие изменения.

$(function() {
  // I could also put both events here if I wanted
  $("#standard-upload-files").on('change', function(event) {
    let files = $(this).val();
    console.log('Change files:', files);
  });

  var dropZone = document.getElementById('drop-zone');
  var filename_list = [];
  dropZone.ondrop = function(e) {
    e.preventDefault();
    for (x = 0; x < e.dataTransfer.files.length; x++) {
      //Gets the list of names from when I dragged images over
      var filename = e.dataTransfer.files[x].name
      //Pushing the list of filenames into an array
      filename_list.push(filename);
      // trigger AND pass, no global needed
      $(this).trigger('got-dropped', [filename_list]);
    }
  }
  //fails as this happens before it is populated
  console.log('filename:', filename_list);
  $('#drop-zone').on('got-dropped', function(event, files) {
    console.log('filename:', filename_list);
    console.log("files:", files);
  });

  $('input[type=file]').val()
  dropZone.ondragover = function(e) {
    return false;
  }

  dropZone.ondragleave = function() {
    return false;
  }
});
h1,
h2,
h3,
h4,
h5 {
  font-weight: 400;
}

.hidden {
  display: none;
}

.wrapper {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.upload-console {
  background: #fefefe;
  border: 2px solid #eee;
  padding: 20px;
}

.upload-console-header {
  padding: 0 0 20px 0;
  margin: 0;
  border-bottom: 2px solid #eee;
  font-weight: 600;
  margin-bottom: 20px;
}

.upload-console-drop {
  height: 200px;
  border: 2px dashed #ccc;
  line-height: 200px;
  color: #ccc;
  text-align: center;
  margin-bottom: 20px;
}

.upload-console-drop.drop {
  border-color: #222;
  color: #222;
}

.upload-console-body {
  margin-bottom: 20px;
}

.bar {
  width: 100%;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, .2);
  box-sizing: border-box;
  margin-bottom: 20px;
}

.bar-fill {
  height: 30px;
  display: block;
  background: cornflowerblue;
  width: 0;
  border-radius: 3px;
  -webkit-transition: width 0.8s ease;
  transition: width 0.8s ease;
}

.bar-fill-text {
  color: #fff;
  line-height: 30px;
  margin-left: 5px;
}

.upload-console-upload {
  border-bottom: 2px solid #ccc;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.upload-console-upload span {
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
  <div class="form-group">
    <label for="title">Title</label>
    <input type="text" class="form-control" name="title">
  </div>
  <div class="form-group">
    <label for="content">content</label>
    <textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
  </div>

  <input type="file" name="files[]" id="standard-upload-files" multiple>
  <input type="submit" value="Upload files" id="standard-upload">
  <div class="wrapper">
    <div class="upload-console">
      <h2 class="upload-console-header">
        Upload
      </h2>

      <div class="upload-console-body">
        <div class="upload-console-drop" id="drop-zone">
          just drag and drop files here
        </div>

        <div class="bar">
          <div class="bar-fill" id="bar-fill">
            <div class="bar-fill-text" id="bar-fill-text"></div>
          </div>
        </div>
        <div class="hidden" id="uploads-finished">
          <h3>Process files</h3>
          <div class="upload-console-upload">
            <a href="#">filename.jpg</a>
            <span>Success</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product" id="add_item">Save</button>
  </div>
</form>
0 голосов
/ 03 ноября 2019

Обратите внимание, что console.log('filename - '+filename_list) всегда будет работать до того, как будут установлены элементы (имена файлов). Это связано с тем, что filename_list заполняется только при вызове события dropZone.ondrop. Если вы действительно хотите использовать обновленный filename_list в другом месте, то есть два пути.

  1. Создайте функцию обратного вызова, которую вы будете вызывать после обновления filename_list
  2. Или вызвать пользовательское событие после обновления filename_list.

Ниже приведена обновленная версия кода. Два метода были продемонстрированы.

     $(document).ready(function(){
    
    var dropZone = document.getElementById('drop-zone');

    var filename_list = [];
    dropZone.ondrop = function(e){
        e.preventDefault();

        for(x = 0; x < e.dataTransfer.files.length; x++)
        {
        //Gets the list of names from when I dragged images over
            var filename = e.dataTransfer.files[x].name
            
            //Pushing the list of filenames into an array
            filename_list.push(filename);
          console.log('sss',filename_list);
             
        }
        
        //1. You pass it to a function 
        yourCallback(filename_list); 
        //2. Or you can triger another event and listen to it elsewhere
        $(this).trigger('filename_updated',[filename_list]) ;
        
    }
    
    //Trying to use the filename array outside of the function
    //A simple callback function
  
    function yourCallback(list){
      console.log('Your filename_list - ',list);

    }
  
  $('#drop-zone').on('filename_updated', function(event, filenameList) {
    console.log("Your filename_list from filename_updated event", filenameList);
    console.log("Your filename_list from global filename_list variable", filename_list);
  });
  
  
    

    dropZone.ondragover = function(e){
        return false;
    }

    dropZone.ondragleave = function(){
        return false;
    }
});
h1,
h2,
h3,
h4,
h5{
  font-weight: 400;
}

.hidden{
  display: none;
}

.wrapper{
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.upload-console{
  background: #fefefe;
  border: 2px solid #eee;
  padding: 20px;
}

.upload-console-header{
  padding: 0 0 20px 0;
  margin: 0;
  border-bottom: 2px solid #eee;
  font-weight: 600;
  margin-bottom: 20px;
}

.upload-console-drop{
  height: 200px;
  border: 2px dashed #ccc;
  line-height: 200px;
  color: #ccc;
  text-align: center;
  margin-bottom: 20px;
}

.upload-console-drop.drop{
  border-color: #222;
  color: #222;
}

.upload-console-body{
  margin-bottom: 20px;
}

.bar{
  width: 100%;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, .2);
  box-sizing: border-box;
  margin-bottom: 20px;
}

.bar-fill{
  height: 30px;
  display: block;
  background: cornflowerblue;
  width: 0;
  border-radius: 3px;
  -webkit-transition: width 0.8s ease;
  transition: width 0.8s ease;
}

.bar-fill-text{
  color: #fff;
  line-height: 30px;
  margin-left: 5px;
}

.upload-console-upload{
  border-bottom: 2px solid #ccc;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.upload-console-upload span{
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" name="title">
    </div>

    <div class="form-group">
        <label for="content">content</label>
        <textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
    </div>

    <input type="file" name="files[]" id="standard-upload-files" multiple>
    <input type="submit" value="Upload files" id="standard-upload">

    <div class="wrapper">
        <div class="upload-console">
            <h2 class="upload-console-header">
                Upload
            </h2>

            <div class="upload-console-body">
                <div class="upload-console-drop" id="drop-zone">
                    just drag and drop files here
                </div>

                <div class="bar">
                    <div class="bar-fill" id="bar-fill">
                        <div class="bar-fill-text" id="bar-fill-text"></div>
                    </div>
                </div>

                <div class="hidden" id="uploads-finished">
                    <h3>Process files</h3>

                    <div class="upload-console-upload">
                        <a href="#">filename.jpg</a>
                        <span>Success</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product" id="add_item">Save</button>
    </div>
</form>

С уважением

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...