實作檔案下載 Servlet
實作檔案下載 Servlet 允許使用者從 Web 應用程式擷取檔案。
如何實作檔案下載:
要啟用檔案下載,我們可以建立一個 servlet 作為下載端點,並將其對應到 web.xml 中的特定 URL。
範例Servlet:
DownloadServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the file ID from the request String id = request.getParameter("id"); // Fetch file metadata from the database String fileName = ""; String fileType = ""; // Set the response content type based on file type response.setContentType(fileType); // Set the content disposition header to prompt download response.setHeader("Content-disposition", "attachment; filename=yourcustomfilename.pdf"); // Create a File object using the file path File file = new File(fileName); // Stream the file to the client InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); // Copy file content in chunks byte[] buffer = new byte[4096]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.flush(); } }
在servlet 的doGet 方法中>
在web.xml 中映射:
<servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping>此設定允許使用者透過傳送對/download?id=
以上是如何用Java實作檔下載Servlet?的詳細內容。更多資訊請關注PHP中文網其他相關文章!