반응형
구현할 것
- 파일선택 버튼 클릭 -> 내 컴퓨터에서 이미지 파일 선택 -> 화면에 이미지, 파일 이름 띄우기
<body> 부분
<body>
<form class="inputImg" method="post" enctype="multipart/form-data"> <!-- 이미지 파일 데이터에 알맞는 enctype 설정 -->
<div class="addImage" id="image-show"> <!-- 이미지 띄울 공간 -->
</div>
<input type="file" accept="image/*" onchange="loadFile(this)">
</form>
</body>
form을 통한 파일 처리
이미지 파일을 받기 위해 enctype을 설정해준다.
input 설정
accept="image/*" : 이미지 형식 모두! 받아올 것이다~
type = "file" : 파일을 받아올 것이기 때문에 꼭 설정해줄 것.
onchange : input이나 select 등의 데이터가 변경될 때 호출되는 이벤트. 위 코드에서는 파일을 불러왔을 때 loadFile함수실행.
<script> 부분
<script>
function loadFile(input) {
let file = input.files[0]; // 선택파일 가져오기
let newImage = document.createElement("img"); //새 이미지 태그 생성
//이미지 source 가져오기
newImage.src = URL.createObjectURL(file);
newImage.style.width = "100%"; //div에 꽉차게 넣으려고
newImage.style.height = "100%";
newImage.style.objectFit = "cover"; // div에 넘치지 않고 들어가게
//이미지를 image-show div에 추가
let container = document.getElementById('image-show');
container.appendChild(newImage);
}
</script>
<style> 부분
<style>
.addImage {
width: 400px;
height: 300px;
background-color: lightgray;
border-radius: 20px 20px / 20px 20px;
overflow: hidden;
margin: 0px 10px 10px 0px;
}
.inputImg {
width: 450px;
height: 350px;
}
</style>
이미지 표시 영역을 원하는 대로 꾸며준다! 별거 없다..
<전체 코드>
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>jQuery, AJAX 연습하기</title>
<!-- jQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
.addImage {
width: 400px;
height: 300px;
background-color: lightgray;
border-radius: 20px 20px / 20px 20px;
overflow: hidden;
margin: 0px 10px 10px 0px;
}
.inputImg {
width: 450px;
height: 350px;
}
</style>
<script>
function loadFile(input) {
let file = input.files[0]; // 선택된 파일 가져오기
let newImage = document.createElement("img"); //새 이미지 추가
//이미지 source 가져오기
newImage.src = URL.createObjectURL(file);
newImage.id = "img-id"
newImage.style.width = "100%";
newImage.style.height = "100%";
newImage.style.objectFit = "cover";
//이미지를 image-show div에 추가
let container = document.getElementById('image-show');
container.appendChild(newImage);
}
</script>
</head>
<body>
<form class="inputImg" method="post" enctype="multipart/form-data"> <!-- 이미지 파일 데이터에 알맞는 enctype 설정 -->
<div class="addImage" id="image-show"> <!-- 이미지 띄울 공간 -->
</div>
<input type="file" accept="image/*" onchange="loadFile(this)">
</form>
</body>
</html>
내 컴퓨터에 있는 이미지 파일을 불러오는 예제를 만들어 보았다. 생각보다 간단하다!
반응형
'기타 공부들' 카테고리의 다른 글
[Python] pymongo 라이브러리로 mongodb 사용하기, pymongo 예제 (0) | 2021.11.03 |
---|---|
[Git] Pycharm과 Git 연동하기 (0) | 2021.11.03 |
[Gitbash] Git 설치 및 사용법 (0) | 2021.11.01 |
[Python] BeautifulSoup으로 크롤링하기 (네이버 영화순위) (0) | 2021.10.11 |
[Javascript] AJAX 사용하기 (0) | 2021.10.08 |