Java Web 開發中數據上傳和下載是一個非常重要的功能,本文將介紹如何實現數據的上傳和下載。
數據上傳:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 獲取上傳的文件 Part part = request.getPart("file"); String fileName = part.getSubmittedFileName(); // 2. 獲取上傳的目錄 String uploadPath = request.getServletContext().getRealPath("upload"); // 3. 創建上傳目錄 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } // 4. 保存上傳的文件 part.write(uploadPath + File.separator + fileName); // 5. 上傳成功后的提示 request.setAttribute("message", "文件上傳成功!"); request.getRequestDispatcher("/message.jsp").forward(request, response); }
數據下載:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 獲取要下載的文件名 String fileName = request.getParameter("fileName"); // 2. 獲取文件所在的目錄 String filePath = request.getServletContext().getRealPath("upload"); File file = new File(filePath, fileName); // 3. 設置響應頭,告訴瀏覽器是下載操作 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 4. 創建輸入輸出流進行文件復制操作 FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) >0) { out.write(buffer, 0, len); } in.close(); out.close(); }
通過上述代碼,數據上傳和下載功能可以輕松實現。需要注意的是,在進行上傳和下載操作時,需要對文件名稱進行編碼,以防止出現中文亂碼等問題。