一丶先引入上傳下載的lib
二丶上傳的的servlet
package com.test.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/upload") public class FileUpLoadAction extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 設置編碼 request.setCharacterEncoding("utf-8"); //對提交的數據進行處理,保存上傳文件 boolean success = processUpload(request); if(success){ //獲取表單text控件的值 String account = request.getAttribute("account").toString(); System.out.println(account); //獲取文件上傳的原始名稱 String fileName = request.getAttribute("upfile").toString(); System.out.println(fileName); //獲取文件上傳後,服務器上保存的名字 String fileNameServer = request.getAttribute("upfileServer").toString(); System.out.println(fileNameServer); request.setAttribute("upfile", fileNameServer); request.setAttribute("message", "上傳成功"); } request.getRequestDispatcher("/upload.jsp").forward(request, response); } private boolean processUpload(HttpServletRequest request) { boolean success = true; String message = null; // 獲取文件需要上傳到的路徑 String path = request.getServletContext().getRealPath("/upload"); System.out.println(path); // 如果此文件夾不存在,則構造此文件夾 File f = new File(path); if (!f.exists()) { f.mkdir(); } // 構造出文件工廠,用於存放JSP頁面中傳遞過來的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置上傳文件的保存路徑 factory.setRepository(f); // 設置緩存大小,如果文件大於緩存大小時,則先把文件放到緩存中 factory.setSizeThreshold(1 * 1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); // 設置可以上傳文件大小的上界20MB upload.setSizeMax(20 * 1024 * 1024); try { // 可以上傳多個文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 獲取表單的屬性名字 String name = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); //解決亂碼問題 value = new String(value.getBytes("iso-8859-1"),"utf-8"); request.setAttribute(name, value); } else { // 獲得文件類型 String contentType = item.getContentType(); // 獲得文件大小 long fileSize = item.getSize(); // 獲取路徑名 String value = item.getName(); // 索引到最後一個反斜槓 int start = value.lastIndexOf("\\"); // 截取 上傳文件的 字符串名字,加1是 去掉反斜槓, String filename = value.substring(start + 1); if (filename != null && !filename.trim().equals("")) { // 如果上傳的文件不是圖片,那麼不上傳 String allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|"; String extName = filename.substring(filename.indexOf("."), filename.length()); if (allImgExt.indexOf(extName + "|") == -1) { message = "該文件類型不允許上傳。請上傳 " + allImgExt + " 類型的文件,當前文件類型為" + extName; success = false; break; } request.setAttribute(name, filename); // 隨機數產生名稱 String newName = System.currentTimeMillis() + extName; request.setAttribute(name + "Server", newName); // 將文件保存到服務器中 InputStream in = item.getInputStream(); // 原文件名 // OutputStream out = new FileOutputStream(new File(path, filename)); // 隨機數文件名 OutputStream out = new FileOutputStream(new File(path, newName)); int length = 0; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } in.close(); out.close(); } } } } catch (FileUploadException e) { message = "文件的內容過大,請上傳小於20MB的文件" ; success = false; e.printStackTrace(); } catch (IOException e) { success = false; e.printStackTrace(); } request.setAttribute("message", message); return success; } }
三丶下載的servlet
package com.test.action; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/download") public class FileDownloadAction extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); // 根據主鍵讀取文件的真實名字 + 服務器上的名字 processDownload("1444442288605.png", "騰訊.png", request, response); } private boolean processDownload(String fileName, String saveName, HttpServletRequest request, HttpServletResponse response) { boolean success = true; // 獲取文件下載所在的路徑 String path = request.getServletContext().getRealPath("/upload"); File fileLoad = new File(path, fileName); // 下載文件 long fileLength = fileLoad.length(); // 文件大小 byte[] buffer = new byte[1024]; // 緩沖字節數組 try { response.reset(); response.setHeader("Content-disposition", "attachment;filename=\"" + new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\""); response.setContentType("application/octet-stream"); response.setHeader("Content_Length", String.valueOf(fileLength)); OutputStream os = response.getOutputStream(); FileInputStream in = new FileInputStream(fileLoad); int hasRead = 0; while ((hasRead = in.read(buffer)) != -1) { os.write(buffer, 0, hasRead); } os.flush(); os.close(); in.close(); } catch (IOException e) { success = false; e.printStackTrace(); } return success; } }
以上所述是小編給大家介紹的JavaWeb中上傳和下載文件實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!