๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JavaScript

[Ajax] ํŒŒ์ผ file ๋‹ค์šด๋กœ๋“œ ๋ฐ›๊ธฐ

by ynzu๐Ÿค 2021. 11. 30.
๋ฐ˜์‘ํ˜•

 

๊ฒฐ๋ก ๋ถ€ํ„ฐ ๋งํ•˜์ž๋ฉด 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

๋Œ“๊ธ€