2016-12-20 2 views
1

이 스크립트를 테스트하는데 여기를 참조하십시오. 하지만 이미지를 선택하면 코드가 표시되지 않으므로 작업 할 수 없습니다.업로드하기 전에 이미지 미리보기를 표시하십시오.

<script> 
jQuery(document).ready(function(e){ 
    jQuery('#file_input').change(function(e) { 
     //alert("okokok"); 
     /**/ 
     readFile(this.files[0], function(e) { 
      //manipulate with result... 
      jQuery('#output_field').text(e.target.result); 
     }); 
    }); 
}); 

function readFile(file, callback){ 
    var reader = new FileReader(); 
    reader.onload = callback 
    reader.readAsText(file); 
} 
</script> 

HTML 코드 :

> <input type="file" id="file_input" class="foo" /> <div > id="output_field" class="foo"></div> 

때 선택 나는 단지 인코딩 단어와 숫자를 표시 할 파일이 아닌 이미지. 어떻게 또는 왜 이런 일이 일어나는 지 모르겠습니다. 그렇지 않으면 당신은 img 요소로 변경해야

jQuery(document).ready(function(e){ 

    jQuery('#file_input').change(function(e) { 

     //alert("okokok"); 



     /**/ 
     readFile(this.files[0], function(e) 
     { 
      //manipulate with result... 
      jQuery('#output_field').src(e.target.result); 
     }); 




     }); 




}); 

function readFile(file, callback){ 
    var reader = new FileReader(); 
    reader.onload = callback 
    reader.readAsDataURL(file); 

} 

#output_field 이미지라고 가정 :

+1

당신은 readAsText를 사용하고 있기 때문에. 이미지를 보여주고 싶다면 img 요소를 만들고 src를'URL.createObjectObjectURL (file)'=>'function showFile (file, callback) {var img = new Image();로 설정하십시오. img.src = URL.createObjectObjectURL (file); (img);};' – Kaiido

답변

0

이 코드를 사용해보십시오. 이 문서는 도움이 될 수 있습니다 : http://www.javascripture.com/FileReader

+0

이 경우 파일 판독기가 필요하지 않습니다.이 경우 브라우저 메모리가 오염 될 것입니다 (콜백 (img);}'콜백은'function callback (img) {$ ('any' 아무것도. 'URL.createObjectURL (file_from_user_device)'는 파일에 대한 직접 포인터이므로 메모리를 차지하지 않습니다. 대부분의 경우 Blob을 dataURL로 변환하는 대신 모든 방법으로 고정해야합니다. – Kaiido

관련 문제