使用Servlet實現檔案下載服務端
阿新 • • 發佈:2019-01-01
場景:使用Servlet實現檔案下載服務端
1.建立spring的web專案,確保啟動正常。
2.建立DownloadServlet類繼承HttpServlet並實現doGet方法。
public class DownloadServlet extends HttpServlet{ private static final Logger logger = LoggerFactory.getLogger(DownloadServlet.class); private static final long serialVersionUID = 1033412753252391835L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("下載開始......"); /**1.從請求中獲取下載名稱*/ String fileName = request.getParameter("filename"); fileName=new String(fileName.getBytes("ISO8859-1"),"UTF-8"); /**2.設定附件形式下載,瀏覽器根據此引數做判斷*/ response.setHeader("Content-Disposition", "attachment;filename="+fileName); /**3.本地存放給服務下載的壓縮資料夾的路徑*/ String dir = "D:/DownloadDir/"; String filePath = dir + fileName; /**4.建立輸入流*/ InputStream in=new FileInputStream(filePath); /**5.從response獲取輸出流*/ ServletOutputStream out=response.getOutputStream(); /**6.把輸入流寫入到輸出流,實際就是一個拷貝過程*/ int len=0; byte [] buffer=new byte[1024 * 4]; while((len=in.read(buffer))>0) { out.write(buffer, 0, len); } in.close(); out.close(); logger.info("下載結束......"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
3.在web.xml中配置Servlet的url對映關係
<!-- 下載服務start --> <servlet> <display-name> </display-name> <servlet-name>downloadServlet</servlet-name> <servlet-class>com.zbz.servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>downloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> <!-- 下載服務end -->
4.啟動服務在瀏覽器訪問
本例是本地搭建服務,直接從D盤讀取一個檔案供下載,
D:\DownloadDir\8195B04F2E924C2E9596AC79488351EF.zip
下載url是:
http://127.0.0.1:8080/study/download?filename=8195B04F2E924C2E9596AC79488351EF.zip
其中: study是專案名稱
以上,TKS.