0

Здравствуйте есть код превью изображений на сайт и проблема в том что кода другое изображение добавляю то оно грузится не там где надо и с повтором первого:

var filestoupload = [];
function previewFiles() {

  var preview = document.querySelector('#preview');
  var files = document.querySelector('input[type=file]').files;

  function readAndPreview(file) {

    // Make sure `file.name` matches our extensions criteria
    if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
      var reader = new FileReader();

      reader.addEventListener("load", function() {
        var image = new Image();
        image.height = 100;
        image.title = file.name;
        image.src = this.result;
        filestoupload.push(this.result)
        var div= document.createElement('div');
        var divdel= document.createElement('div');
        divdel.className='delete'
        divdel.innerHTML='<i class="fa fa-times" aria-hidden="true"></i>'
        div.className='fileprew'
        div.appendChild(divdel);
        div.appendChild(image);
        preview.appendChild(div);
        console.log('files to upload: ', filestoupload.length)
        
      }, false);

      reader.readAsDataURL(file);
    }

  }

  if (files) {
    [].forEach.call(files, readAndPreview);
    
  }

}
$('body').on("click", ".delete", function() {
  
  index=$(this).index();
  console.log('удаляем файл: ',index)
  filestoupload.splice(index, 1);
  $(this).parent().remove();
  console.log('files to upload: ', filestoupload.length)

});
.upload-file-container:first-child { 
  margin-left: 0;
} 

.upload-file-container > img {
  width: 160px;
    height: 160px;
    margin-left: 55px;
    border-radius: 55%;
}

.upload-file-container-text{
  font-family: Arial, sans-serif;
  font-size: 12px;
  color: #719d2b;
  line-height: 17px;
  text-align: center;
  display: block;
  position: absolute; 
  left: 0; 
  bottom: 0; 
  width: 100px; 
  height: 35px;
}
.upload-file-container-two:first-child { 
  margin-left: 0;
} 

.upload-file-container-two > img {
  width: 160px;
    height: 160px;
    margin-left: 55px;
    border-radius: 55%;
}

.upload-file-container-text-two{
  font-family: Arial, sans-serif;
  font-size: 12px;
  color: #719d2b;
  line-height: 17px;
  text-align: center;
  display: block;
  position: absolute; 
  left: 0; 
  bottom: 0; 
  width: 100px; 
  height: 35px;
}


.file_upload_two {
    overflow: hidden;
    background: #eee;
    border: 1px solid #ccc;
    font-size: 23px;
    line-height: 1.65;
    text-align: center;
    /* padding: 20px; */
    width: 95px;
    top: 96px;
    height: 40px;
    width: 60vw;
    margin-left: 14px;
    border-radius: 20px;
    border-color: rgba(0, 0, 255, 0.18);
    color: #efefef;
    background-color: rgb(30, 190, 190);
    text-shadow: -1px 0px 2px black;
    font-family: sans-serif;
    font-weight: bold;
    transition: all 0.3s cubic-bezier(.25,.8,.25,1);
}
 .file_upload_two:hover {
box-shadow: 0px 2px 2px 1px #6a6666;
    color: white;
    cursor: pointer;
 }
.file_upload_two input[type=file] {
  position: relative;
    top: -40px;
    line-height: 0px;
    right: 0;
    font-size: 200px;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer;
    height: 0;
    cursor: pointer;
}

.file_upload {
    overflow: hidden;
    background: #eee;
    border: 1px solid #ccc;
    font-size: 23px;
    line-height: 1.65;
    text-align: center;
    /* padding: 20px; */
    width: 95px;
    top: 96px;
    height: 40px;
    width: 30vw;
    margin-left: 14px;
    border-radius: 20px;
    border-color: rgba(0, 0, 255, 0.18);
    color: #efefef;
    background-color: rgb(30, 190, 190);
    text-shadow: -1px 0px 2px black;
    font-family: sans-serif;
    font-weight: bold;
    transition: all 0.3s cubic-bezier(.25,.8,.25,1);
}
 .file_upload:hover {
box-shadow: 0px 2px 2px 1px #6a6666;
    color: white;
    cursor: pointer;
 }
.file_upload input[type=file] {
  position: relative;
    top: -40px;
    line-height: 0px;
    right: 0;
    font-size: 200px;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer;
    height: 0;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="preview"></div>


<br>
<div class="file_upload"> Добавить<input type="file" class="photo" id="photo" name="photo[]" onchange="previewFiles()" multiple/></div>
<br><br><br>
<div class="file_upload_two"><i class="fa fa-camera" aria-hidden="true"></i> Подгрузить документы<input type="file" class="photoDoc" id="doc" name="doc[]" onchange="previewFiles()" multiple/></div>
    </div>
    <div id="preview"></div>
  </div>

2
  • Что значит "не там где надо"? В сниппете нормально добавляются изображения, без повторов.
    – br3t
    22 фев 2017 в 14:26
  • попробуйте сначала добавить одну фотографию через кнопку добавить, а вторую через кнопку подгрузить при этом пусть это будет два разных изоражения
    – Vlad
    22 фев 2017 в 15:48

1 ответ 1

0

Ваша проблема в том, что

var files = document.querySelector('input[type=file]').files;

всегда обращается к первому инпуту. Так что даже если вы добавляете изображение через второй, то в preview падает картинка из первого.

Избежать этого можно, передавая контекст (инпут, для которого вызывается readAndPreview), либо навесить один EventListener на инпуты и использовать полноценный this. В первом случае код будет такой:

var filestoupload = [];

function previewFiles(context) { // пробрасываем контекст

  var preview = document.querySelector('#preview');
  var files = context.files; // используем контекст

  function readAndPreview(file) {

    // Make sure `file.name` matches our extensions criteria
    if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
      var reader = new FileReader();

      reader.addEventListener("load", function() {
        var image = new Image();
        image.height = 100;
        image.title = file.name;
        image.src = this.result;
        filestoupload.push(this.result);
        var div = document.createElement('div');
        var divdel = document.createElement('div');
        divdel.className = 'delete';
        divdel.innerHTML = '<i class="fa fa-times" aria-hidden="true"></i>';
        div.className = 'fileprew';
        div.appendChild(divdel);
        div.appendChild(image);
        preview.appendChild(div);
        console.log('files to upload: ', filestoupload.length);

      }, false);

      reader.readAsDataURL(file);
    }

  }

  if (files) {
    [].forEach.call(files, readAndPreview);

  }

}
$('body').on("click", ".delete", function() {

  index = $(this).index();
  console.log('удаляем файл: ', index);
  filestoupload.splice(index, 1);
  $(this).parent().remove();
  console.log('files to upload: ', filestoupload.length);

});
.upload-file-container:first-child {
  margin-left: 0;
}

.upload-file-container>img {
  width: 160px;
  height: 160px;
  margin-left: 55px;
  border-radius: 55%;
}

.upload-file-container-text {
  font-family: Arial, sans-serif;
  font-size: 12px;
  color: #719d2b;
  line-height: 17px;
  text-align: center;
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100px;
  height: 35px;
}

.upload-file-container-two:first-child {
  margin-left: 0;
}

.upload-file-container-two>img {
  width: 160px;
  height: 160px;
  margin-left: 55px;
  border-radius: 55%;
}

.upload-file-container-text-two {
  font-family: Arial, sans-serif;
  font-size: 12px;
  color: #719d2b;
  line-height: 17px;
  text-align: center;
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100px;
  height: 35px;
}

.file_upload_two {
  overflow: hidden;
  background: #eee;
  border: 1px solid #ccc;
  font-size: 23px;
  line-height: 1.65;
  text-align: center;
  /* padding: 20px; */
  width: 95px;
  top: 96px;
  height: 40px;
  width: 60vw;
  margin-left: 14px;
  border-radius: 20px;
  border-color: rgba(0, 0, 255, 0.18);
  color: #efefef;
  background-color: rgb(30, 190, 190);
  text-shadow: -1px 0px 2px black;
  font-family: sans-serif;
  font-weight: bold;
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.file_upload_two:hover {
  box-shadow: 0px 2px 2px 1px #6a6666;
  color: white;
  cursor: pointer;
}

.file_upload_two input[type=file] {
  position: relative;
  top: -40px;
  line-height: 0px;
  right: 0;
  font-size: 200px;
  opacity: 0;
  filter: alpha(opacity=0);
  cursor: pointer;
  height: 0;
  cursor: pointer;
}

.file_upload {
  overflow: hidden;
  background: #eee;
  border: 1px solid #ccc;
  font-size: 23px;
  line-height: 1.65;
  text-align: center;
  /* padding: 20px; */
  width: 95px;
  top: 96px;
  height: 40px;
  width: 30vw;
  margin-left: 14px;
  border-radius: 20px;
  border-color: rgba(0, 0, 255, 0.18);
  color: #efefef;
  background-color: rgb(30, 190, 190);
  text-shadow: -1px 0px 2px black;
  font-family: sans-serif;
  font-weight: bold;
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.file_upload:hover {
  box-shadow: 0px 2px 2px 1px #6a6666;
  color: white;
  cursor: pointer;
}

.file_upload input[type=file] {
  position: relative;
  top: -40px;
  line-height: 0px;
  right: 0;
  font-size: 200px;
  opacity: 0;
  filter: alpha(opacity=0);
  cursor: pointer;
  height: 0;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview"></div>
<br>
<div class="file_upload"> Добавить<input type="file" class="photo" id="photo" name="photo[]" onchange="previewFiles(this)" multiple/></div>
<br><br><br>
<div class="file_upload_two"><i class="fa fa-camera" aria-hidden="true"></i> Подгрузить документы<input type="file" class="photoDoc" id="doc" name="doc[]" onchange="previewFiles(this)" multiple/></div>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.