Cute Running Puppy

๐ŸƒSpring/Logic

# FileInputStream - ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ ์ฒ˜๋ฆฌ

๋ญ‰์ง€๋ง˜ 2025. 2. 17. 09:31

ํŒŒ์ผ์„ ์˜ฌ๋ ธ์œผ๋ฉด ๋‹ค์šด๋กœ๋“œ๋ฅผ ๋ฐ›์„ ์ˆ˜ ์žˆ๊ฒŒ ์ฒ˜๋ฆฌํ•ด์•ผํ–ˆ๋‹น..

<a href="๊ฒฝ๋กœ?ํ‚ค๊ฐ’=${ํ…Œ์ด๋ธ”.ํ‚ค๊ฐ’}">
	${file.orgFileName}
</a>

 

์ผ๋‹จ ์•ž๋‹จ์—์„œ aํƒœ๊ทธ์— ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์„ค์ •ํ•ด์ฃผ๊ณ 

ํŠน์ • ํŒŒ์ผ์„ ์กฐํšŒํ•˜๋Š” ๋กœ์ง์„ ๋งŒ๋“ ๋‹ค.. (mapper..service..)

 

๊ทธ๋Ÿฐ๋‹ค์Œ ์ปจํŠธ๋กค๋Ÿฌ์— ๋ทฐ๋‹จ์— ์„ค์ •ํ•œ ๊ฒฝ๋กœ๋กœ ์š”์ฒญ์ด ๋“ค์–ด์™”์„ ๋•Œ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผ ํ•˜๋Š”๋ฐ

ํŒŒ์ผ ์ •๋ณด๋ฅผ ์•„๊นŒ ๋งŒ๋“  ํŠน์ • ํŒŒ์ผ์„ ์กฐํšŒํ•˜๋Š” ๋กœ์ง์œผ๋กœ ํ™•์ธํ•˜๊ณ 

ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ๊ฐ€์ง€๊ณ  ํŒŒ์ผ์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค์Œ

 

 ์•„๋ž˜์ฒ˜๋Ÿผ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ์— ํ•„์š”ํ•œ ์‘๋‹ตํ—ค๋”๋ฅผ ์„ค์ •ํ•ด์•ผ ํ–ˆ๋‹ค.

response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition",
        "attachment; filename=\"" + URLEncoder.encode(fileDTO.getOrgFileName(), "UTF-8") + "\"");

 

๊ทธ๋Ÿฐ ๋‹ค์Œ ํŒŒ์ผ์ธํ’‹์ŠคํŠธ๋ฆผ์œผ๋กœ ํŒŒ์ผ์„ ์ฝ๊ณ 

response.getOutputStream()์„ ์ด์šฉํ•ด ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†กํ•œ๋‹ค.

FileInputStream fis = new FileInputStream(file);
     OutputStream os = response.getOutputStream()) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    os.flush();

 

๊ทธ๋–„ ๋ฒ„ํผ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ 1KB์”ฉ ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ์–ด ์ŠคํŠธ๋ฆผ์œผ๋กœ ์ „์†กํ•œ๋‹ค.

flush()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ๋ชจ๋“  ๋ฐ์ดํ„ฐ๊ฐ€ ํด๋ผ์ด์–ธํŠธ๋กœ ์ „์†ก๋œ๋‹ค.

 

์—๋Ÿฌ๊ฐ€ ๋‚ ๋ถ€๋ถ„์— ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ์ž˜ ํ•ด์ฃผ์žฅ..!