servlet編碼下載檔案
阿新 • • 發佈:2019-01-14
import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 編碼下載 */ public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取下載檔案的名稱 String filename=request.getParameter("name"); //上下文 ServletContext context=getServletContext(); //1.設定檔案的mimeType型別 String mimeType=context.getMimeType(filename); response.setContentType(mimeType); //2.設定下載的頭資訊 response.setHeader("content-disposition", "attachment;filename"+filename); //3.提供流 //源 InputStream is=context.getResourceAsStream("/download/"+filename); //目的 ServletOutputStream sos=response.getOutputStream(); int len=-1; byte[] buf=new byte[1024]; while((len=is.read(buf))!=-1){ sos.write(buf, 0, len); } sos.close(); is.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }