다운로드
클릭시 비동기로 요청보내는 형식을 이용한다.
<img src="../download?fileLoca=폴더경로&uuid=랜덤값&filename=파일명">
or
<img th:src="@{ ../download(filepath=${imgs.filepath}, uuid=${imgs.uuid}, filename=${imgs.filename} )}">
이미지 불러오기와 코드가 유사하다.
ResponseEntity의 header.add가 수정되면 된다.
"Content-Disposition", "attachment; filname=" + filename
Content-Disposition, attachment; : 브라우저에게 어떻게 처리할지 알려주는 아주 중요한 정보. attachment인 경우 다운로드됨
filname=파일명.확장자 : 해당파일의 확장자가 반드시 포함되어야 한다.
productList.html
...
<a href="#" class="normal_btn modalOn">이미지수정</a></td>
...
<div class="filebox preview-image">
...
<script src="/js/modal.js"></script>
<!-- 1.modalOn클래스가 들어가면 모달창오픈, 2.modalOn()으로 켤 수 있음 -->
<!-- 모달창 제어 -->
<script>
//이미지 수정버튼을 클릭했을 때. modalOn()
$(".modalOn").click((e)=>{
e.preventDefault(); //a링크의 고유이벤트 중지
//1.클릭한 대상의 prod_id값
var prod_id=$(e.target).closest("td").next().html();
//2.post방식으로 img데이터 조회
$.ajax({
url:"../getProductImg",
type:"post",
data:JSON.stringify({prod_id:prod_id}),//데이터
contentType:"application/json",//보내는데이터타입
success:(result)=>{
console.log(result); //반환된 데이터
var str = "";
var arr=['a','b','c'];
for(var i=0;i<result.length;i++){
str+='<div class="left">';
str+='<span>추가이미지</span>';
str+='<label class="upload-display" for="'+arr[i]+'_file">';
str+='<span class="upload-thumb-wrap">';
str+='<img class="upload-thumb" src="'+'../display/'+result[i].filepath+'/'+result[i].uuid+'/'+result[i].filename+'">';
str+='</span>';
str+='</label>';
str+='<input class="upload-name" value="파일선택" disabled="disabled">';
str+='<input type="file" name="file" id="'+arr[i]+'_file" class="upload-hidden">';
str+='<input type="hidden" value="">';
str+='<input type="hidden" value="">';
str+='<button type="button" class="normal_btn" style="display: block;">삭제</button>';
str+='<button type="button" class="normal_btn" style="display: block;" onclick="location.href='+"'"+'../download/'+result[i].filepath+'/'+result[i].uuid+'/'+result[i].filename+"'"+'">다운로드</button>';
str+='</div>';
}
$(".filebox").html(str);
},
error:(err)=>{alert("이미지 조회에 실패했습니다.");}
});
//modalOn();
});
</script>
의
str+='<button type="button" class="normal_btn" style="display: block;"
onclick="location.href='+"'"+'../download/'+result[i].filepath+'/'+result[i].uuid+'/'+result[i].filename+"'"+'">
다운로드
</button>';
를 통해 컨트롤러와 연결
AjaxController.java
//다운로드기능 -
@GetMapping("/download/{filepath}/{uuid}/{filename}")
public ResponseEntity<byte[]> download(@PathVariable("filepath")String filepath,
@PathVariable("uuid")String uuid,
@PathVariable("filename")String filename) {
//파일이 저장된 경로
String savename = uploadpath+"\\"+filepath+"\\"+uuid+"_"+filename;
File file = new File(savename);
//저장된 이미지파일의 이진데이터 형식을 구함
byte[] result=null;//1. data
ResponseEntity<byte[]> entity=null;
try {
result = FileCopyUtils.copyToByteArray(file);
//2. header
HttpHeaders header = new HttpHeaders();
//다운로드임을 명시
header.add("Content-Disposition", "attachment; filename="+filename);
//3. 응답본문
entity = new ResponseEntity<>(result,header,HttpStatus.OK);//데이터, 헤더, 상태값
} catch (IOException e) {
e.printStackTrace();
}
return entity;
}
에서
header.add("Content-Disposition", "attachment; filename="+filename);
를 통해 다운로드가 가능해지는 것.
attachment가 있어서 다운로드.
filename에 확장자가 포함되어 있다.
service-mapper-sql로 연결할 필요가 없다. 정보만 있다면 컨트롤러에서 처리하여 다운로드를 만드는 것이 가능함.
'Spring Boot' 카테고리의 다른 글
230223 Spring Boot 인터셉터-메뉴핸들러 (0) | 2023.02.23 |
---|---|
230223 Spring Boot 세션-인터셉터 (0) | 2023.02.22 |
230222 Spring Boot 이미지파일 불러오기 (0) | 2023.02.22 |
230221 Spring Boot 이미지 등록하기, @Transactional, selectKey (0) | 2023.02.21 |
230221 Spring Boot 파일 업로드-썸네일 이미지 (0) | 2023.02.21 |