[Vue.js] 사용자 파일첨부 취소시 이미지 데이터 초기화 (event.target)

Yeoonnii·2022년 11월 16일
0

Vue

목록 보기
9/13

프로젝트 게시글 서비스 구현시 게시글 등록시 이미지는 무조건 1개 이상을 첨부해야 하도록 설계하였다.

사용자가 이미지를 첨부했다가 취소하는 경우 유효성 검사에 걸려 게시글이 등록되지 않아야 하는데,
게시글 등록 버튼 클릭시 직전에 첨부를 취소했던 이미지와 함께 게시글이 등록되어버리는 문제가 발생했다.

사용자가 게시글에 이미지를 첨부 한 뒤 취소하는 경우,
event를 이용하여 첨부되었던 이미지 데이터를 reset 해주어야 한다

template

	<el-form-item label="첨부이미지">
		<input type="file" multiple @change="handleFile($event)" style="margin-left: 70px;" />
	</el-form-item>

1. handleFile($event)

state.file의 변수에 수동으로 첨부 이미지 정보를 넣기

  • 첨부한 파일이 존재하지 않는 경우 state.filenull 값을 주어 초기화 시켜준다
  • if조건은 파일이 존재하는 경우 e.target.files != null 와 파일이 존재하지 않는 경우로 나눈다

event.target을 이용하면 현재 이벤트가 발생한 요소의 속성들을 얻을 수 있다.

        //state.file의 변수에 수동으로 첨부 이미지 정보를 넣기
        const handleFile = (e) =>{
            console.log("******** e.target.files => ", e.target.files);
            if(e.target.files.length == 0 ) { // 첨부한 파일이 존재하지 않는 경우
                state.file = null; // 초기화
                console.log("******** state.file => " , state.file)
            }
            else { // 첨부한 파일이 존재하는 경우
                for(let i=0; i<e.target.files.length; i++){
                    state.file[i] = e.target.files[i];
                }
            }


콘솔창에서 아래와 같이 state.file 변수가 초기화 되는것을 확인할 수 있다



1. handleInsert()

게시글 등록하기 (글정보만 등록)
유효성 검사시 state.file== null 인 경우로 판단한다

 // 게시글 등록(글정보만)
        const handleInsert = async () => {

            if(state.file == null ){
                alert('이미지는 반드시 한장이상 첨부되어야 합니다!');
                return false;
            }

            if(state.title===''){
                alert('제목을 입력하세요.');
                form.value[0].focus();
                return false;
            }
            
            if(state.content===''){
                alert('내용을 입력하세요.');
                form.value[1].focus();
                return false;
            }

            const url = `/ROOT/api/board/insertboardone.json`;
            const headers = {
                "Content-Type":"application/json",
                "TOKEN" : state.token
            }
            const body = {   //userid 가져와서 닉네임 받아야함
                title    : state.title,
                content  : state.content, // 이미지를 표시하는 태그만 포함
                userid   : state.userid
            }

            const {data} = await axios.post(url, body, {headers});
            console.log(data);
            if(data.status === 200) {
                console.log('이미지를 등록할 글번호 => ',data.bno)
                handleIMGInsert(data.bno);
            }
            else{
                alert('등록에 실패하였습니다.');
                router.push({path:'/boardwrite'});
            }   
        };

### 2. handleIMGInsert()
        // 이미지 등록 
        const handleIMGInsert = async(bno) => {
            console.log('전달받은 이미지를 등록할 글번호 => ',bno)
            console.log('등록할 이미지 정보 => ',state.file)
            console.log('등록할 이미지의 길이 => ', state.file.length)
            const url = `/ROOT/api/board/boardinsertbatchimage.json`;
            const headers ={
                "Content-Type":"multipart/form-data"
            };
            // 이미지가 있는 경우  body 정보 담기
            let body = new FormData();
            for(let i=0; i<state.file.length; i++){
                body.append("file", state.file[i]);
                body.append("bno", bno);
            }
            // console.log(body)
            const { data }  = await axios.post(url, body, headers);
            console.log(data);
            if(data.status == 200){
                alert('게시글이 등록되었습니다!')
                 router.push({path:'/board'});
            } 
            else{
                alert('게시글 등록에 실패하였습니다.\n다시 시도해주세요');
            }
        };

0개의 댓글