Skip to content

Instantly share code, notes, and snippets.

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 leejongyoung/b83ad2be09ebca81473a9e25c3151306 to your computer and use it in GitHub Desktop.
Save leejongyoung/b83ad2be09ebca81473a9e25c3151306 to your computer and use it in GitHub Desktop.
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Base64;
@RestController
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(HttpServletRequest request) throws UnsupportedEncodingException {
String fileName = "파일명 예시.txt";
String encodedFileName = null;
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
// Internet Explorer, Edge 브라우저인 경우
encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
} else {
// Chrome, Firefox 등 그 외 브라우저인 경우
encodedFileName = "=?UTF-8?B?" + Base64.getEncoder().encodeToString(fileName.getBytes("UTF-8")) + "?=";
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
// 파일 리소스 및 콘텐츠 타입 설정
Resource resource = ...;
return ResponseEntity.ok()
.headers(headers)
.body(resource);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment