一個(gè)好用的下載文件的實(shí)現方法,好多朋友喜歡自己控制輸出流來(lái)實(shí)現下載,但是那種方法非常容易出問(wèn)題,而且不能使用下載工具進(jìn)行下載,利用這種方式還可以使用下載工具進(jìn)行下載,也不用擔心輸出流有問(wèn)題,因為是web容器控制的, jsp文件只有兩個(gè)參數,一個(gè)是下載對話(huà)框提示要保存的文件名,一個(gè)是文件做在服務(wù)器上面的相對路徑,點(diǎn)擊下載后頁(yè)面不僅不會(huì )跳轉,還會(huì )彈出文件保存對話(huà)框,還支持目標另存為或使用下載工具進(jìn)行下載. <a herf='X.jsp?fileName=a.doc&filePath=x/a.doc'>點(diǎn)擊下載</a>
view plaincopy to clipboardprint?
<%
String filePath = "/"+request.getParameter("path");
String fileName = request.getParameter("name");
if(fileName!=null&&filePath!=null){
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
try{
out.clear();
out=pageContext.pushBody();
}catch(Throwable e){
e.printStackTrace();
}
try{
RequestDispatcher dis = application.getRequestDispatcher(filePath);
dis.forward(request,response);
}catch(Throwable e){
e.printStackTrace();
}finally{
response.flushBuffer();
}
}
%>
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。