在實現文件上傳和下載以前咱們須要作一些準備工做,在Apache官網去下載文件上傳下載的兩個組件,下載連接這裏給出:common-fileupload組件下載:http://commons.apache.org/proper/commons-fileupload/css
common-io組件下載:http://commons.apache.org/proper/commons-io/根據本身需求下載對應版本html
1、建立工程前端
將所須要的兩個開發包導入到工程項目中如圖:java
2、代碼編寫web
1.前端頁面代碼apache
1). 在WebRoot目錄下新建一個fileUpload.jsp頁面,用來上傳文件瀏覽器
1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'fileUpload.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <!-- 文件上傳表單的提交方式必須是「post」 編碼類型必須爲:enctype="multipart/form-data" --> 27 <form action="UploadServlet" method="post" enctype="multipart/form-data"> 28 29 username: <input type="text" name="username" /><br> 30 file: <input type="file" name="file"><br> 31 file2: <input type="file" name="file2"><br> 32 <input type="submit" value="上傳文件"> 33 34 </form> 35 36 </body> 37 </html>
2). 新建一個fileUploadResult.jsp頁面用來顯示結果信息安全
1 <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="GB18030"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'fileUploadResult.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <%-- 27 <% 28 //獲取流對象 29 InputStream inputStream = request.getInputStream(); 30 31 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 32 33 String buffer = null; 34 35 while((buffer = br.readLine()) != null){ 36 out.print(buffer + "<br>"); 37 } 38 39 br.close(); 40 inputStream.close(); 41 42 %> 43 --%> 44 ${message}<br> 45 46 EL-username : ${requestScope.username} <br> 47 EL-file1 : ${requestScope.file }<br> 48 EL-file2 : ${requestScope.file2}<br> 49 50 </body> 51 </html>
2. 編寫上傳文件處理的Servlet代碼app
1) UploadServlet.java代碼以下:jsp
1 package com.Servlet; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.PrintWriter; 8 import java.util.List; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 import org.apache.commons.fileupload.FileItem; 16 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 19 public class UploadServlet extends HttpServlet { 20 21 /** 22 * The doPost method of the servlet. <br> 23 * 24 * This method is called when a form has its tag value method equals to post. 25 * 26 * @param request the request send by the client to the server 27 * @param response the response send by the server to the client 28 * @throws ServletException if an error occurred 29 * @throws IOException if an error occurred 30 */ 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 34 35 //獲得上傳文件的保存目錄,將上傳的文件放在webRoot目錄下(可是通常爲了安全放在WEB-INF目錄下,不容許外界直接訪問,保證上傳的安全) 36 String path = this.getServletContext().getRealPath("/upload"); 37 38 File file = new File(path); 39 40 //判斷上傳文件的保存目錄是否存在 41 if(!file.exists() && !file.isDirectory()){ 42 System.out.println(path + "目錄不存在,須要建立!"); 43 //建立目錄 44 file.mkdir(); 45 } 46 //消息提示 47 String message = ""; 48 try{ 49 //使用Apache文件上傳組件處理文件上傳步驟: 50 //1.建立一個DiskFileItemFactory工廠 51 DiskFileItemFactory factory = new DiskFileItemFactory(); 52 //2.建立一個文件上傳解析器 53 ServletFileUpload upload = new ServletFileUpload(factory); 54 //解決中文亂碼 55 upload.setHeaderEncoding("UTF-8"); 56 //3.判斷提交的數據普通表單的數據仍是帶文件上傳的表單 57 if(!upload.isMultipartContent(request)){ 58 //若是是表單數據普通表單,則按照傳統方式獲取數據 59 return ; 60 } 61 //4.使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個List<FileItem>集合,每個FileItem對應一個Form表單的輸入項 62 List<FileItem> list = upload.parseRequest(request); 63 for(FileItem item : list){ 64 //若是fileItem中封裝的是普通輸入項的數據 65 if(item.isFormField()){ 66 //獲取字段名字 67 String name = item.getFieldName(); 68 //解決普通輸入項中中文亂碼問題 69 String value = item.getString("UTF-8");//value = new String(value.getBytes("iso8859-1"),"UTF-8"); 70 System.out.println(name + " = " + value); 71 }else{ //若是表單中提交的是上傳文件 72 //得到上傳的文件名稱 73 String filename = item.getName(); 74 System.out.println(filename); 75 if(filename == null || filename.trim().equals(" ")){ 76 continue; 77 } 78 //注意:不一樣的瀏覽器提交的文件名稱是不同的,有些瀏覽器提交的文件會帶有路徑,如「D:\\project\WebRoot\hello.jsp」,有一些是單純的文件名:hello.jsp 79 //去掉獲取到文件名中的路徑名,保留單純的文件名 80 filename = filename.substring(filename.lastIndexOf("\\") + 1); 81 //獲取item中的上傳文件的輸入流 82 InputStream in = item.getInputStream(); 83 //建立一個文件輸入流 84 FileOutputStream out = new FileOutputStream(path + "\\" + filename); 85 //建立一個緩衝區 86 byte buffer[] = new byte[1024]; 87 //判斷輸入流中的數據是否已經讀取完畢的標誌位 88 int len = 0; 89 //循環將輸入流讀入到緩衝區當中,(len = in.read(buffer)>0)就表示in裏面還有數據存在 90 while((len = in.read(buffer)) > 0){ 91 //使用FileOutputStream輸出流將緩衝區的數據寫入到指定的目錄(path+"\\"+filename)當中 92 out.write(buffer, 0, len); 93 } 94 //關閉輸入流 95 in.close(); 96 //關閉輸出流 97 out.close(); 98 //刪除處理文件上傳生成的臨時文件 99 item.delete(); 100 message = "文件上傳成功!"; 101 102 103 } 104 } 105 106 }catch(Exception e){ 107 message = "文件上傳失敗!"; 108 e.printStackTrace(); 109 } 110 111 request.setAttribute(message, message); 112 request.getRequestDispatcher("fileUploadResult.jsp").forward(request, response); 113 114 } 115 116 }
2)web.xml文件中的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 6 <servlet> 7 8 <servlet-name>UploadServlet</servlet-name> 9 <servlet-class>com.Servlet.UploadServlet</servlet-class> 10 </servlet> 11 12 <servlet-mapping> 13 <servlet-name>UploadServlet</servlet-name> 14 <url-pattern>/UploadServlet</url-pattern> 15 </servlet-mapping> 16 17 </web-app>
結果:
摘自:https://www.cnblogs.com/xdp-gacl/p/4200090.html