๋ฐ์ํ
๊ฒฐ๋ก ๋ถํฐ ๋งํ์๋ฉด xhr.responseType = "blob" ๋ก ์ค์ ํด์ผ ํ๋ค!
๊ธฐ์กด์ ์ฌ์ฉํ๋ ์ ์ด์ฟผ๋ฆฌ ๋ฒ์ ์ด 1.11.1์ด์๋๋ฐ ์ด ๋ฒ์ ์ blob์ด ์ ์ฉ์๋๋๋ผ..
๋ฒ์ ๋ฌธ์ ์ธ์ค ๋ชจ๋ฅด๊ณ ํ์ฐธ์ ์จ๋ฆ ํ๋๋ฐ 3.6.0์ผ๋ก ์ฌ๋ฆฌ๋๊น ํด๊ฒฐ๋๋ค. (์ด๋ค ๋ฒ์ ๋ถํฐ ๋๋ ๊ฑด์ง๋ ๋ชจ๋ฅด๊ฒ ์)
์๋ ์์ ์ฐธ์กฐ!!
let options = {
url: "[[@{/}]]download"
, beforeSubmit : loadingAjaxImage
, contentType: "application/x-www-form-urlencoded;charset=UTF-8"
, xhr: function () {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//response ๋ฐ์ดํฐ๋ฅผ ๋ฐ์ด๋๋ฆฌ๋ก ์ฒ๋ฆฌํ๋ค. ์ธํ
ํ์ง ์์ผ๋ฉด default๊ฐ text
xhr.responseType = "blob";
};
return xhr;
}
, type: "post"
, success: function (data, message, xhr) {
hideAjaxImage();
if (xhr.readyState == 4 && xhr.status == 200) {
// ์ฑ๊ณตํ์๋๋ง ํ์ผ ๋ค์ด๋ก๋ ์ฒ๋ฆฌํ๊ณ
let disposition = xhr.getResponseHeader('Content-Disposition');
let filename;
if (disposition && disposition.indexOf('attachment') !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
let blob = new Blob([data]);
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}else{
//์คํจํ์๋๋ alert ๋ฉ์์ง ์ถ๋ ฅ
alertPopup("๋ค์ด๋ก๋์ ์คํจํ์์ต๋๋ค.");
}
}
};
$("#testForm").ajaxSubmit( options );
}
ajax๋ก ๋ฐ๊พผ ์ด์
๋๋์ ๋ฐ์ดํฐ๋ผ ์์ฑํ๊ณ ๋ค์ด๋ก๋ ์ฒ๋ฆฌํ๋ ์๊ฐ์ด ์ค๋ ๊ฑธ๋ฆฌ๊ธฐ ๋๋ฌธ์ ๋ก๋ฉ์ด๋ฏธ์ง๋ฅผ ํธ์ถํ๊ธฐ ์ํด์๋ค
beforeSubmit : loadingAjaxImage -> ๋ก๋ฉ ์ด๋ฏธ์ง ํธ์ถํ๋ ๋ถ๋ถ
Controller ์์
@RequestMapping("/download")
public ResponseEntity<?> download(@ModelAttribute TestVo testVo, HttpSession session){
FileVo vo = this.testService.download(testVo);
if(vo.getFileData() != null) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + vo.getFileName() + "\"")
.body(vo.getFileData());
}else{
return ResponseEntity.noContent().build();
}
}
์ด๋ ๊ฒ ํ์ผ์ด ๋ค์ด๋ก๋ ๋๋ค!
728x90
๋ฐ์ํ
'๊ฐ๋ฐ > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] var, let, const ๋น๊ต - var is used instead of let or const (1) | 2022.01.24 |
---|
๋๊ธ