實作一個簡單的檔案下載Servlet
要實作一個簡單的檔案下載Servlet,請依照下列步驟操作:
建立一個Servlet:
實作 Servlet :
這是一個 Servlet 實作範例:
public class DownloadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); // Retrieve file name and type using ID from database response.setContentType("fileType"); response.setHeader("Content-disposition", "attachment; filename=yourcustomfilename.pdf"); File file = new File("fileName"); OutputStream out = response.getOutputStream(); try (FileInputStream in = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } finally { out.flush(); } } }
以上是如何實作一個簡單的檔案下載Servlet?的詳細內容。更多資訊請關注PHP中文網其他相關文章!