주요 코드만, main.js 링크
$(document).ready(function(){
$('#photo').change(function(){
// 사진 미리보기
// 1. 사진을 선택하면 서버로 업로드한다 → 링크를 걸어서 사진을 보여줌
// 2. 내 컴퓨터에 있는 사진을 js로 읽어와서 미리보기
// 파일 1개를 업로드할 때 js로 파일 객체에 접근 :
// document.getElementById('photo').files[0];
// d:/aaa/성적.html
const file = $('#photo')[0].files[0];
// 위에서 생성한 파일 객체와 RileReader js 내장객체를 이용해 파일 읽어오기
const reader = new FileReader();
// FileReader에서 일반 파일로 읽어와 문자열 형식으로 변환
// readAsDataURL()은 비동기 메소드(병렬수행)
reader.readAsDataURL(file);
// console.log(reader.result); null출력
// FileReader의 로딩이 끝나면
reader.onload = function(){
$('#show_photo').attr('src',reader.result);
}
});
})
주요 코드만, main.js링크
function loadPhoto(){
const file = $('#photo')[0].files[0];
const MAX_SIZE = 1024*1024;
if(file.size>MAX_SIZE) {
// return false를 하면 loadphoto 함수는 중간에 종료
// 하지만 <input type='file' id='photo'>
// 에서는 여전히 파일이 선택되어 있다.
$('#photo').val("");
// 출력중인 사진을 지우려니 높이가 0이 되는 문제가 발생
// 그래서 <img>를 <div>안에 넣고, <img>삭제 후 다시 붙여주기
$('#show_photo_area').empty();
$('<img height="300px">').attr('id','show_photo')
.appendTo(4('#show_photo_area'));
return false;
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
$('#show_photo').attr('src', reader.result);
}
}
function inputCheck(){
// 필수입력체크 → 패턴 체크 → 오류메시지 출력 후 return false
// → 체크성공했다면 js 객체 리턴
const name = $('#name').val();
const tel = $('#tel').val();
const address = $('#address').val();
const namePattern = /^[A-Za-z]{4,10}$/;
const telPattern = /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/;
if(name==''){
alert('이름은 필수 입력입니다.');
return false;
} else if(namePattern.test(name)==false){
alert('이름은 알파벳 4~10자 입니다');
return false;
} else if(tel==""){
alert('연락처는 필수 입력입니다.');
return false;
} else if(telPattern.test(tel)==false){
alert('연락처는 000-1234-5678 형식입니다.');
return false;
} else if(address==""){
alert('주소는 필수 입력입니다.');
return false;
}
return { name, tel, address };
}
$(document).ready(function(){
const querystring = location.search.substr(1,5);
if(querystring=='error') alert('연락처 추가 실패');
$('#photo').change(loadPhoto);
$('#join').click(function(){
const params = inputCheck();
const photo = $('#photo')[0].files[0];
if(params==false) return false;
$.ajax({
url: 'http://sample.bmaster.kro.kr/contacts/',
method: 'post',
data: params,
success: function(response){
// 응답코드가 200 - 서버 에러발생 아님
if(response.status=="success"){
if(photo!=undefined){
const formData = new FormData();
formData.append('photo',photo);
$.ajax({
url: 'http://sample.bmaster.kro.kr/contacts/'
+response.no + '/photo',
method: 'post',
data: formData,
processData: false,
contentType: false,
success:function(){
location.href="read.html?no=" + response.no;
}
})
} else {
// 연락처를 추가했고 프사를 업로드하지는 않는다.
location.href = 'read.html?no=' + response.no;
}
} else if(response.status=="fail"){
location.href = 'join.html?error';
}
}
});
});
});
주요 코드만, main.js 링크
// POST / contacts: name, tel, address, 이미지없음 urlencoded
// POST / contacts/{연락처번호}/photo.이미지업로드 form-data
function loadPhoto(){
const file = $('#photo')[0].files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
$('#show_photo').attr('src', reader.result);
}
}
$(document).ready(function(){
// join.html?error에 대한 처리를 작성하시오
const querystring = location.search.substr(1,5);
if(querystring=='error') Swal.fire('실패', '재가입필요', 'error');
$('#photo').change(loadPhoto);
$('#join').click(function(){
// 프사를 선택하지 않은 경우 $('#photo')[0].files[0]는 undefined
// 회원가입 → 성공했고 프사를 선택하지 않은 경우 → list.html'
// → 실패한 경우 → join.html?error
// → 성공했고 프사를 선택한 경우 → 프사 업로드 성공
// → list.html
// 프사 업로드 실패 → read.html
const params = {
name: $('#name').val(),
tel: $('#tel').val(),
address: $('#address').val()
};
$.ajax({
url: 'http://sample.bmaster.kro.kr/contacts/',
method: 'post',
data: params,
success:function(response){
if(response.status=="success"){
if($('#photo')[0].files[0]!=undefined){
// <form enctype='multipart/form-data'></form>
const formData = new FormData();
formData.append('photo', $('#photo')[0].files[0]);
$.ajax({
url:'http://sample.bmaster.kro.kr/contacts/'
+ response.no + '/photo',
method: 'post',
data: formData,
processData: false,
contentType: false,
success:function(){
locoation.href="list.html";
}
})
} else {
location.href = "read.html?no=" + response.no;
}
} else if(respone.status="fail"){
location.href="join.html?error";
} else {
console.log('잘못된 코드');
}
}
})
})
})