📄 filedownloadservlet.java
字号:
package com.oa.struts.document.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownloadServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//request.setCharacterEncoding("");
String filename = request.getParameter("filename");
// System.out.println("=====" + new String(filename.getBytes("ISO-8859-1"), "gb2312"));
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(filename.getBytes("gb2312"), "ISO-8859-1"));
bis = new BufferedInputStream(new FileInputStream(
getServletContext().getRealPath("ImagesUploaded/" + filename)));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
throw new ServletException("文件下载出错!"+e.getMessage());
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -