Programing

HTML-파일 이름을 선택한 후 이미지 표시

lottogame 2020. 6. 19. 19:25
반응형

HTML-파일 이름을 선택한 후 이미지 표시


가능한 중복 :
이미지를 업로드하기 전에 미리보기

저와 함께 할 수있는 양식이 있습니다

<input type="file" name="filename" accept="image/gif, image/jpeg, image/png">

파일을 찾아보고 선택합니다.

내가하고 싶은 것은 이미지가 선택된 직후 이미지를 표시하는 것입니다. 그리고 이것은 폼의 "제출"버튼을 누르기 전에 이미지가 클라이언트쪽에 거의 상주하게됩니다. 이것을 할 수 있습니까?


여기 있습니다 :

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

스크립트:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

라이브 데모


다음 코드를 사용하여이를 달성 할 수 있습니다.

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

데모 : http://jsfiddle.net/ugPDx/


HTML5를 사용하여 수행 할 수 있지만 HTML5를 지원하는 브라우저에서만 작동합니다. 다음은 입니다.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

참고URL : https://stackoverflow.com/questions/12368910/html-display-image-after-selecting-filename

반응형