반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 게시판insert
- 스프링게시판목록조회
- HTML
- 톰캣9.0다운로드
- 스프링게시판상세보기
- url설정
- 스프링게시판만들기
- 스프링프로젝트
- 스프링게시판등록
- mysqlinsert한글깨짐
- 저장할때한글깨짐
- 한글깨짐해결방법
- Could not create the java Virtual Machine
- 이클립스db연결
- 게시판목록조회
- 전자정부프레임워크 double-submit
- mybatis연결
- 스프링게시판insert
- 게시판상세보기
- 톰캣시작페이지설정
- oracle
- dataSource설정
- 이클립스데이터베이스연결
- double-submit
- Java
- 자바스크립트
- insert할글깨짐
- insert 중복방지
- 컨트롤러url
- 게시판만들기
Archives
- Today
- Total
하루의 일상💜
[자바스크립트] 첨부파일 누르면 원하는 사진 썸네일로 만들기 본문
반응형
이미지 파일을 첨부할 때 원본사이즈를 올리게 되면 용량때문에 로딩시간이 길어지게 된다.
그렇기 때문에 이미지 사이즈를 조절하여 올리게 되는 것을 썸네일이라고 하는데 첨부파일을 통해서
원하는 이미지로 설정하는 방법에 대해서 알아보겠다.
주로 사이트에서 프로필사진 설정같은 곳에서 주로 쓰이게 된다.
첨부파일 클립이미지 넣기
<body>
<label for="attach">
<div>
</div>
</label>
<input type="file" id="attach" style="display: none;">
</body>
먼저 HTML 에서 input 첨부파일 버튼을 만들어 줘야 한다.
내가 원하는 이미지르 넣기 위해서 display를 none으로 설정 해줘야 기존의 버튼이 사라지고 이미지를 넣을 수 있다.
CSS 스타일 주기
<style>
label[for='attach'] div {
width: 150px;
height: 150px;
background-image: url("img/clip.png");
background-size: 100%;
background-repeat: no-repeat;
cursor: pointer;
}
</style>
CSS 에서 label의 div 를 불러온 후 설정한다.
background 이미지를 넣을 때에는 무조건 사이즈를 정해줘야하고 해당 div요소에 맞게 100%를 준다.
background-repeat: no-repeat;
첨부한 이미지가 div 크기에 맞지 않게 설정될 경우 이미지가 repeat(반복해서 생기는 현상)가 될 수 있기 때문에 no-repeat 로 설정을 주었다.
javascrip 설정하기
크롬이라는 브라우저에서는 우리가 설정한 경로를 썼을 때 보안상으로 접근이 금지된다.
그렇기 때문에 절대경로는 쓸 수 없게 되는데 크롬브라우저에서 절대경로를 암호화된 URL을 제공해준다.
암호화된 경로를 javascript 파일로 입력해줘야하고 그 경로를 reader 를 사용하여 읽어올 수 있다.
const file = document.querySelector("input[type='file']");
//업로드한 input의 파일을 객체화시켜서 가져온다
file.addEventListener("change", function(e){
//위의 객체화 시킨 file이 change(파일이 업로드 되었을 때) 됐을때 함수를 실행시킨다.
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
//업로드한 파일을 읽어와서 암호화된 URL 정보를 얻을 수 있다.
reader.onload = function(e){
//전달받은 파일을 모두 로딩했을 때
let url = e.target.result;
//암호화된 절대 경로를 가져와서
if(url.includes("image")){
//이미지 파일인지 검사한다.
document.querySelector("label div").style.backgroundImage = "url(" + url +")";
//이미지 파일이 맞다면 선택한 이미지로 대체
}else{
document.querySelector("label div").style.backgroundImage = "url(no-image.jpg)";
//이미지 파일이 아니라면 준비해놓은 이미지(no-photo)로 대체
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>첨부파일 썸네일</title>
<style>
label[for='attach'] div {
width: 150px;
height: 150px;
background-image: url("img/clip.png");
background-size: 100%;
background-repeat: no-repeat;
cursor: pointer;
}
</style>
</head>
<body>
<label for="attach">
<div>
</div>
</label>
<input type="file" id="attach" style="display: none;">
</body>
<script>
const file = document.querySelector("input[type='file']");
file.addEventListener("change", function(e){
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = function(e){
let url = e.target.result;
if(url.includes("image")){
document.querySelector("label div").style.backgroundImage = "url(" + url +")";
}else{
document.querySelector("label div").style.backgroundImage = "url(no-image.jpg)";
}
}
});
</script>
</html>
반응형
'자바스크립트' 카테고리의 다른 글
[자바스크립트] 슬라이드배너 화면이동 버튼 적용하기 prev, next, btns (0) | 2022.10.17 |
---|---|
[자바스크립트] 한글을 숫자로 변경, 숫자를 한글로 변경 (1) | 2022.10.07 |
[자바스크립트] 1~100까지 객체에 담은 후 짝수만 출력 (0) | 2022.10.06 |
[자바스크립트] 문자열 함수, 포함여부 includes(), split(), substring(), === (1) | 2022.10.06 |
[자바스크립트] forEach(), indexOf(), map(), filter() (0) | 2022.10.06 |