2017-12-15 12 views
0

이미지 축소판 및 선택한 파일을 삭제하기위한 제거 버튼을 추가하고 싶습니다. 내가 어떻게 해?업로드 된 여러 파일에 버튼을 추가/삭제하는 방법은 무엇입니까?

window.imagePreview = function (t) { 
    if (t.files && t.files[0]) { 
     for (var i = 0; t.files.length >= i; i++) { 
      var reader = new FileReader(); 
      reader.onload = function (e) { 
       $('#image-preview').append('<img src="' + this.result + '"/>'); 
      }; 

      reader.readAsDataURL(t.files[i]); 
     } 
    } 
} 

CSS :이

JS 내 코드입니다

.btn-file{ 
    position: relative; 
} 
.btn-file input[type=file] { 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    right: 0; 
    left: 0; 
    opacity: 0; 
} 

#image-preview { 
    width: 100%; 
    max-height: 260px; 
    height: 260px; 
    overflow-y: auto; 
    background-color: #F0F0F0; 
    border: 1px dashed #928f8f; 
    border-radius: 4px; 
    margin-bottom: 10px; 
} 


#image-preview img { 
    max-width: 120px; 
    max-height: 120px; 
    display: inline-block; 
    margin: 5px; 
} 

HTML :

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<div id="image-preview"></div> 
    <span class="btn btn-primary btn-file"> 
    <input type="file" name="file[]" id="file" class="" multiple onchange="imagePreview(this)" style="width: 0;height: 0;"> 
     Select Files 
    </span> 

JSfiddle

그리고이 오류 해결 방법 : 그것은 당신이 원하는 경우이 코드

Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'

답변

0

체크 아웃 참조하십시오. 당신은 루프가 한 번 더하고 어떤 파일 데이터를 사용할 수는 없다 실행 마지막 실행의 원인이되는 t.files.length >= i을 설정하기 때문에 그런데

window.imagePreview = function (t) { 
    if (t.files && t.files[0]) { 
     for (var i = 0; t.files.length > i; i++) { 
      var reader = new FileReader(); 
      reader.onload = function (e) { 
       var thumbnail = '<div>'; 
        thumbnail += '<img class="image" src="' + e.target.result + '"/>'; 
        thumbnail += '<button class="removeButton">Remove File</button>'; 
        thumbnail += '</div>'; 
       $('#image-preview').append(thumbnail); 

       $(".removeButton").on("click", function(){ 
        $(this).closest('div').remove(); 
        document.getElementById("file").value = ""; 
       }); 

      }; 
      reader.readAsDataURL(t.files[i]); 
     } 
    } 
} 

, 당신이있어 오류입니다.

JSfiddle

+0

감사합니다. 확인해 보겠습니다. –