<div class="download-container" onclick="fileDownload('<%=n.getFilePath()%>');">
<!-- 클릭할때마다 파일 명을 보내줌 -->
<img src="<%=request.getContextPath()%>/images/file.png" width="20">
<span><%=n.getFilePath()%></span>
</div>
<script>
const fileDownload=(filename)=>{
location.assign("<%=request.getContextPath()%>/fileDownload.do?name="+filename);
}
</script>
package com.web.notice.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/fileDownload.do")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileDownloadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName=request.getParameter("name");
String path = getServletContext().getRealPath("/upload/notice/");
File f = new File(path+fileName);
FileInputStream fis=new FileInputStream(f);
BufferedInputStream bis=new BufferedInputStream(fis);
String fileRename="";
String header=request.getHeader("user-agent");
boolean isMSIE=header.indexOf("MSIE")!=-1 || header.indexOf("Trident")!=-1;
if(isMSIE) {
fileRename=URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+","%20");
}else {
fileRename=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="+fileRename);
ServletOutputStream sos=response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(sos);
int read=-1;
while((read=bis.read())!=-1) {
bos.write(read);
}
bis.close();
bos.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}