준비물
#SpringBoot
#vue.js
#axios
#formData

#application.yml

 

 


1. application.yml 에다가 아래처럼 선언해주시고

default properties
	spring:
		application:
		name: "project"
		profiles:
		active: local
	servlet: # 파일업로드 추가
		multipart:
		file-size-threshold: 1MB
		location: C:/경로 ****/frontend/public/upload/
		max-file-size: 100MB
		max-request-size: 100MB

 

 

2. 화면

- ** Html태그에서 multipart/어쩌구 form 으로 감싸줄필요 없음, Json 형태라 그냥 아래서 formData 로 변환

 

<dl class="option_list clfix">
	<dt>
		<span>이미지업로드</span>
	</dt>
<dd>
<div class="input-container">
	<input v-on:change="$fileSelect()" type="file" ref="imgFile"  />
</div>

 

3. 스크립트 

// 파일 첨부시 Change이벤트
$fileSelect : function $fileSelect(){
	this.scndhandReg.imgFile = this.$refs.imgFile.files[0];
}


// 저장전. 밸리데이션 체크하는 로직,, 필요에 따라서,,사용
$beforeSave : function $beforeSave () {
	const _this = this;
	_this.$validator.validateAll().then((isValid) => {
	if(isValid){
		if(commonUtils.$confirm('신청하시겠습니까?')){
			this.scndhandReg.area = this.scndhandReg.local;            
			_this.$executeSave();    // 저장**            
                }
            } else {
                commonUtils.$alertValidationError(_this.$validator);
            }
        });
    },
    
    
// 저장
$executeSave : function $executeSave () {

        const url = constant.boardFoHost + '/scndH경로(예)dManage/v1.0.0/scnd경로(예)anage';    // ex 컨트롤러 Post경로 


        // Object To FormData 변환
        var formData = new FormData();
        formData.append("sj"        , this.scndhandReg.sj);         // 컨트롤러 넘길 정보 예 1
        formData.append("area"        , this.scndhandReg.area);     // 컨트롤러 넘길 정보 예 2            
        // 이미지 
        if(this.scndhandReg.imgFile != ""){                    
            formData.append("imgFile"    , this.scndhandReg.imgFile);    // 이미지 파일 ^^
        }


        // 파일업로드시 (경로,FormData,Header) 설정       
        this.$axios.post(url, formData, { headers: {'Content-Type': 'multipart/form-data'}}).then(
                 response => {
            if(!!response && response.status === 200){
            
                commonUtils.$alert('감사합니다.\n정상등록되었습니다.');
                this.scndhandReg = Object.assign({}, this.defScndhangReg);

            }
        }).catch( error => {
        console.log(error);
            commonUtils.$alertUncatchedError(error);
        });
    },

 

 

4. 컨트롤러 

-- @ModelAttribute ScndHandManage 형태로 받는다,

@PostMapping("/v1.0.0/scndHandManage")
public ResponseEntity insertScndHandManage(
		@ModelAttribute ScndHandManage scndHandManage){
		return ResponseUtils.createSuccessResponseEntity(this.scndHandManageService.insertScndHandManage(scndHandManage));
}

 

5. 모델 객체

private String sj;
private String area;
private MultipartFile imgFile; // 이미지 파일도 받을수 있게 하나 추가 해주고 **

 

5. 임플

 

// Impl 상단에
@Value("${spring.servlet.multipart.location}")
private String FILE_PATH;
// 선언 해주면 위 application.yml에 선언된 경로 참조한다.



Path path = Paths.get(FILE_PATH + scndHandManage.getImgFile().getOriginalFilename()); // Save Path 생성
scndHandManage.getImgFile().transferTo(path); // 업로드



 

6. 화면에서 불러오기 

 

<img class="product-thumb" v-bind:src="'/upload/'+scndhand.urlInfo" />

이미지 저장경로는 보통 favicon.ico 와 index.html 이 있는 

public 폴더안에 upload 폴더를 생성하였고 (application.yml 참고)

 

 

다른곳에 이미지 저장후 불러오려면 설정을 해야된다. 그건 다음에....

 

 

 

 

 

 

 

 

+ Recent posts