javaweb下載文件模板
阿新 • • 發佈:2017-09-05
div read ade pro logs etc isp pos tac
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class DownloadServlet */ public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取需要下載文件名稱 String filename = request.getParameter("filename"); //獲取下載的類型 response.setContentType(this.getServletContext().getMimeType(filename)); //告知客戶端需要下載 response.setHeader("Content-Disposition", "attachment;filename="+filename); //獲取文件的絕對路徑 String path = this.getServletContext().getRealPath("download/"+filename); //獲取文件的輸入源 InputStream in = new FileInputStream(path); //獲取輸出流 ServletOutputStream out = response.getOutputStream();int len=0; byte[] buffer = new byte[1024]; while((len=in.read(buffer))>0) { out.write(buffer,0,len); } in.close(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
javaweb下載文件模板