📄 downloadservlet.java
字号:
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.URLEncoder;
public class DownloadServlet extends HttpServlet {
private String contentType = "application/x-msdownload";
private String enc = "utf-8";
private String fileRoot = "";
private Logger log = Logger.getLogger(MarkServlet.class.getName());
public void init(ServletConfig config) throws ServletException {
String tempStr = config.getInitParameter("contentType");
if (tempStr != null && !tempStr.equals("")) {
contentType = tempStr;
}
tempStr = config.getInitParameter("enc");
if (tempStr != null && !tempStr.equals("")) {
enc = tempStr;
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
String filePath="";
if((String)request.getParameter("filePath")!=null){
filePath=(String)request.getParameter("filePath");
log.debug("filePath :"+filePath);
}else{
filePath=request.getSession().getServletContext().getRealPath("/export/");
log.debug("filePath :"+filePath);
}
String fileName =(String)request.getParameter("fileName");
File file = new File(filePath,fileName);
if (file.exists()) {
String filename = URLEncoder.encode(fileName, enc);
response.reset();
response.setContentType(contentType);
response.addHeader("Content-Disposition", "attachment; filename=\""
+ filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
if (fileLength != 0) {
InputStream inStream=null;
ServletOutputStream servletOS=null;
try{
inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
}catch(Exception e){
log.error(e,e);
}finally{
try{
inStream.close();
servletOS.flush();
servletOS.close();
}catch(Exception e){
log.error(e,e);
}
}
}
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -