<입력 파일>에서 <img>로 이미지로드


90

요소를 통해 사용자가 선택한 이미지를로드하려고합니다.

다음과 같이 입력 요소에 onchange 이벤트 핸들러를 추가했습니다.

<input type="file" name="picField" id="picField" size="24" onchange="preview_2(this);" alt=""/>

그리고 preview_2 함수는 다음과 같습니다.

var outImage ="imagenFondo";
function preview_2(what){
    globalPic = new Image();
    globalPic.onload = function() {
        document.getElementById(outImage).src = globalPic.src;
    }
    globalPic.src=what.value;
}

여기서 outImage에는 새 사진을로드 할 태그의 id 값이 있습니다.

그러나 온로드가 발생하지 않으며 html에 아무것도로드하지 않는 것으로 보입니다.

어떻게해야합니까?


답변:


106

File API를 지원하는 브라우저 에서 FileReader 생성자를 사용 하여 사용자가 선택한 파일을 읽을 수 있습니다.

document.getElementById('picField').onchange = function (evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;

    // FileReader support
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
            document.getElementById(outImage).src = fr.result;
        }
        fr.readAsDataURL(files[0]);
    }

    // Not supported
    else {
        // fallback -- perhaps submit the input to an iframe and temporarily store
        // them on the server until the user's session ends.
    }
}

브라우저 지원

  • IE 10
  • Safari 6.0.2
  • 크롬 7
  • Firefox 3.6
  • 오페라 12.02

파일 API가 지원되지 않는 경우 대부분의 보안에 민감한 브라우저에서 파일 입력 상자에서 파일의 전체 경로를 가져올 수 없으며 데이터에 액세스 할 수도 없습니다. 유일한 실행 가능한 솔루션은 양식을 숨겨진 iframe에 제출하고 파일을 서버에 미리 업로드하는 것입니다. 그런 다음 요청이 완료되면 이미지의 src를 업로드 된 파일의 위치로 설정할 수 있습니다.


맞습니다. 사용자가 선택한 이미지를 단순히 들리는 것처럼 업로드 할 수있는 방법이 없습니다 ...?
Valentina

1
예, 저는 x- 브라우저 솔루션을 찾고 있으므로 서버 옵션을 사용하여 시도해 볼 것입니다. 대단히 감사합니다!
Valentina

1
왜 이것을 객체 URL이 아닌 DataURL로 변환하는지 궁금합니다.
ShrekOverflow

5
동기 버전을 원하면 다음을 사용할 수 있습니다 URL.createObjectURL(document.getElementById("fileInput").files[0]);..
Константин Ван

1
@ КонстантинВан URL.revokeObjectURL메모리 누수를 방지 하려면 호출해야합니다 ! developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
Dai

53

iEamin이 대답에서 말했듯이 HTML 5는 이제 이것을 지원합니다. 그가 준 링크 인 http://www.html5rocks.com/en/tutorials/file/dndfiles/ 는 훌륭합니다. 다음은 해당 사이트의 샘플을 기반으로 한 최소 샘플이지만 더 자세한 예는 해당 사이트를 참조하십시오.

onchangeHTML에 이벤트 리스너를 추가합니다 .

<input type="file" onchange="onFileSelected(event)">

ID가있는 이미지 태그를 만듭니다 ( height=200이미지가 화면에 너무 크지 않도록 지정 합니다).

<img id="myimage" height="200">

다음은 onchange이벤트 리스너 의 JavaScript입니다 . File로 전달 된 객체를 가져 와서 내용을 읽기 위해 event.target.files[0]a FileReader를 구성 하고 결과 data:URL을 img태그 에 할당하는 새 이벤트 리스너를 설정합니다 .

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

훌륭한 링크! 스크립트에 대해 제시 한 코드는 정의되어 있지 않습니다.
rashadb 2015 년

14

$('document').ready(function () {
    $("#imgload").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#imgshow').attr('src', e.target.result);
            }
            reader.readAsDataURL(this.files[0]);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">

그것은 jQuery에서 나를 위해 작동합니다.


'imgload'와 'imgshow'가 미리 정의되어 있지 않은 경우 어떻게 사용하나요? 서버에서 반환 된 5 쌍의 파일 입력 및 이미지 홀더가 있고 해당 ID는 서버 코드에서도 반환되는 일부 인덱스를 기반으로 생성된다고 가정 해 보겠습니다.
이반

7

ES2017 방식

// convert file to a base64 url
const readURL = file => {
    return new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = e => res(e.target.result);
        reader.onerror = e => rej(e);
        reader.readAsDataURL(file);
    });
};

// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);

const preview = async event => {
    const file = event.target.files[0];
    const url = await readURL(file);
    img.src = url;
};

fileInput.addEventListener('change', preview);


1

Andy E는이를 수행하는 HTML 기반 방법이 없다는 것이 옳습니다 *; 하지만 Flash를 사용하고 싶다면 할 수 있습니다. 다음은 Flash가 설치된 시스템에서 안정적으로 작동합니다. 앱이 iPhone에서 작동해야하는 경우 당연히 대체 HTML 기반 솔루션이 필요합니다.

* ( 2013 년 4 월 22 일 업데이트 : HTML은 이제 HTML5에서이를 지원합니다. 다른 답변을 참조하세요.)

플래시 업로드에는 다른 장점도 있습니다. 플래시는 대용량 파일의 업로드가 진행됨에 따라 진행률 표시 줄을 표시하는 기능을 제공합니다. (내가 틀렸을 수도 있지만, 뒤에서 Flash를 사용함으로써 Gmail이 그렇게하는 방식이라고 확신합니다.)

다음은 사용자가 파일을 선택하여 표시 할 수있는 Flex 4 앱 샘플입니다.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

명확히 말하면, 보안이 걱정되는 사람들을 위해 : Flash에서는 로컬 파일에 액세스 할 수 없습니다. 사용자가 명시 적으로 대화 형으로 지정한 로컬 파일에만 액세스 할 수 있습니다. 이는 HTML이 수행하는 작업 (명시 적으로 지정된 파일을 서버에 업로드 할 수 있음)과 유사하지만 Flash에서 파일 업로드 기능 외에 로컬 액세스도 허용한다는 점이 다릅니다.
Mike Morearty

실행 가능한 Flash 앱을 여기에 업로드하여 사용해 볼 수 있습니다. morearty.com/preview/FileUploadTest.html
Mike Morearty

1

var outImage ="imagenFondo";
function preview_2(obj)
{
	if (FileReader)
	{
		var reader = new FileReader();
		reader.readAsDataURL(obj.files[0]);
		reader.onload = function (e) {
		var image=new Image();
		image.src=e.target.result;
		image.onload = function () {
			document.getElementById(outImage).src=image.src;
		};
		}
	}
	else
	{
		    // Not supported
	}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>preview photo</title>
</head>

<body>
<form>
	<input type="file" onChange="preview_2(this);"><br>
	<img id="imagenFondo" style="height: 300px;width: 300px;">
</form>
</body>
</html>

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.