Skip to content

Instantly share code, notes, and snippets.

@ayaysir
Created August 8, 2019 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayaysir/eccfa88d92a8a34e7efac85f2ce1a1a4 to your computer and use it in GitHub Desktop.
Save ayaysir/eccfa88d92a8a34e7efac85f2ce1a1a4 to your computer and use it in GitHub Desktop.
file download controller for Spring Boot
package com.example.thymeleaf;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class TestController {
@RequestMapping("/filedownload")
@ResponseStatus(HttpStatus.OK) // Thymeleaf 사용시 이것을 사용해야 에러가 발생하지 않음
public void fileDownloadOnWebBroweser(HttpServletRequest req, HttpServletResponse res) throws Exception {
File f = new File("track.pptx");
String downloadName = null;
String browser = req.getHeader("User-Agent");
//파일 인코딩
if(browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")){
//브라우저 확인 파일명 encode
downloadName = URLEncoder.encode(f.getName(), "UTF-8").replaceAll("\\+", "%20");
}else{
downloadName = new String(f.getName().getBytes("UTF-8"), "ISO-8859-1");
}
res.setHeader("Content-Disposition", "attachment;filename=\"" + downloadName +"\"");
res.setContentType("application/octer-stream");
res.setHeader("Content-Transfer-Encoding", "binary;");
try(FileInputStream fis = new FileInputStream(f);
ServletOutputStream sos = res.getOutputStream(); ){
byte[] b = new byte[1024];
int data = 0;
while((data=(fis.read(b, 0, b.length))) != -1){
sos.write(b, 0, data);
}
sos.flush();
} catch(Exception e) {
throw e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment