2023年11月28日发(作者:)
jsp如何实现下载文件的功能
第一步:创建Servlet
第二步:写代码
public class FielDownLoad extends HttpServlet {
/**
* Constructor of the object.
*/
public FielDownLoad() {
super();
}
/**
* The doPost method of the servlet.
*
* 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 {
String filename = ameter("file_name");
if (filename == null)
filename = "";
filename = ();
InputStream inStream = null;
String attchname = "";
byte[] b = new byte[100];
int len = 0;
try {
attchname = getAttachName(filename); //取得附件的名称
filename = getRealName(request, filename); //取得附件的全路径
if (filename == null) {
tentType("text/html; charset=GBK");
ter().print("文件不存在,或者禁止下载!");
return;
}
attchname = toUtf8String(attchname); //将文件转码 UTF-8
inStream = new FileInputStream(filename);
(); //必须reset,否则会出现文件不完整
SmartUpload su = new SmartUpload(); // 新建一个SmartUpload对象
lize(vletConfig(), request, response); // 初始化
// 设定contentDisposition为null以禁止浏览器自动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
tentDisposition(null);
adFile(filename); // 下载文件
//循环取出流中的数据
while ((len = (b)) > 0) {
putStream().write(b, 0, len);
}
();
} catch (Exception e) {
tackTrace();
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
//取得附件的名称
public static String getAttachName(String filename) {
if (filename == null)
return "";
filename = ();
int pos = 0;
pos = dexOf("");
if (pos > -1) {
filename = ing(pos + 1);
}
pos = dexOf("/");
if (pos > -1) {
filename = ing(pos + 1);
}
pos = dexOf(tor);
if (pos > -1) {
filename = ing(pos + 1);
}
return filename;
}
//UTF8转码
public static String toUtf8String(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < (); i++) {
char c = (i);
if (c >= 0 && c <= 255) {
(c);
} else {
byte[] b;
try {
b = ng(c).getBytes("utf-8");
} catch (Exception ex) {
n(ex);
b = new byte[0];
}
for (int j = 0; j < ; j++) {
int k = b[j];
if (k < 0)
k += 256;
("%" + tring(k).toUpperCase());
}
}
}
String s_utf8 = ng();
(0, ());
gth(0);
sb = null;
return s_utf8;
}
//取得下载文件的真实全路径名称
private String getRealName(HttpServletRequest request, String filename) {
if (request == null || filename == null)
return null;
filename = ();
if ((""))
return null;
String filepath = lPath(filename);
if (filepath == null)
return null;
File file = new File(filepath);
if (!())
return null;
return filepath;
}
}


发布评论