java檔案上傳下載功能實現代碼_java

來源:互聯網
上載者:User

本文執行個體為大家分享了檔案上傳下載java實現代碼,供大家參考,具體內容如下

前台:

1. 提交方式:post
2. 表單中有檔案上傳的表單項: <input type=”file” />
3. 指定表單類型:
    預設類型:enctype="application/x-www-form-urlencoded"
    檔案上傳類型:multipart/form-data

FileUpload

檔案上傳功能開發中比較常用,apache也提供了檔案上傳組件!
FileUpload組件:
1. 下載源碼
2. 項目中引入jar檔案
commons-fileupload-1.2.1.jar 【檔案上傳組件核心jar包】
commons-io-1.4.jar 【封裝了對檔案處理的相關工具類】

使用:

public class UploadServlet extends HttpServlet { // upload目錄,儲存上傳的資源 public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  /*********檔案上傳組件: 處理檔案上傳************/  try {   // 1. 檔案上傳工廠   FileItemFactory factory = new DiskFileItemFactory();   // 2. 建立檔案上傳核心工具類   ServletFileUpload upload = new ServletFileUpload(factory);   // 一、設定單個檔案允許的最大的大小: 30M   upload.setFileSizeMax(30*1024*1024);   // 二、設定檔案上傳表單允許的總大小: 80M   upload.setSizeMax(80*1024*1024);   // 三、 設定上傳表單檔案名稱的編碼   // 相當於:request.setCharacterEncoding("UTF-8");   upload.setHeaderEncoding("UTF-8");   // 3. 判斷: 當前表單是否為檔案上傳表單   if (upload.isMultipartContent(request)){    // 4. 把請求資料轉換為一個個FileItem對象,再用集合封裝    List<FileItem> list = upload.parseRequest(request);    // 遍曆: 得到每一個上傳的資料    for (FileItem item: list){     // 判斷:普通文本資料     if (item.isFormField()){      // 普通文本資料      String fieldName = item.getFieldName(); // 表單元素名稱      String content = item.getString();  // 表單元素名稱, 對應的資料      //item.getString("UTF-8"); 指定編碼      System.out.println(fieldName + " " + content);     }     // 上傳檔案(檔案流) ----> 上傳到upload目錄下     else {      // 普通文本資料      String fieldName = item.getFieldName(); // 表單元素名稱      String name = item.getName();   // 檔案名稱          String content = item.getString();  // 表單元素名稱, 對應的資料      String type = item.getContentType(); // 檔案類型      InputStream in = item.getInputStream(); // 上傳檔案流      /*       * 四、檔案名稱重名       * 對於不同使用者readme.txt檔案,不希望覆蓋!       * 幕後處理: 給使用者添加一個唯一標記!       */      // a. 隨機產生一個唯一標記      String id = UUID.randomUUID().toString();      // b. 與檔案名稱拼接      name = id +"#"+ name;      // 擷取上傳基路徑      String path = getServletContext().getRealPath("/upload");      // 建立目標檔案      File file = new File(path,name);      // 工具類,檔案上傳      item.write(file);      item.delete(); //刪除系統產生的臨時檔案      System.out.println();     }    }   }   else {    System.out.println("當前表單不是檔案上傳表單,處理失敗!");   }  } catch (Exception e) {   e.printStackTrace();  } } // 手動實現過程 private void upload(HttpServletRequest request) throws IOException,   UnsupportedEncodingException {  /*  request.getParameter(""); // GET/POST  request.getQueryString(); // 擷取GET提交的資料   request.getInputStream(); // 擷取post提交的資料 */  /***********手動擷取檔案上傳表單資料************/  //1. 擷取表單資料流  InputStream in = request.getInputStream();  //2. 轉換流  InputStreamReader inStream = new InputStreamReader(in, "UTF-8");  //3. 緩衝流  BufferedReader reader = new BufferedReader(inStream);  // 輸出資料  String str = null;  while ((str = reader.readLine()) != null) {   System.out.println(str);  }  // 關閉  reader.close();  inStream.close();  in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  this.doGet(request, response); }}

案例:

Index.jsp

<body>   <a href="${pageContext.request.contextPath }/upload.jsp">檔案上傳</a>      <a href="${pageContext.request.contextPath }/fileServlet?method=downList">檔案下載</a> </body>

Upload.jsp

<body>   <form name="frm_test" action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data">   <%--<input type="hidden" name="method" value="upload">--%>   使用者名稱:<input type="text" name="userName"> <br/>  檔案: <input type="file" name="file_img"> <br/>  <input type="submit" value="提交">  </form> </body>

FileServlet.java

/** * 處理檔案上傳與下載 * @author Jie.Yuan * */public class FileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  // 擷取請求參數: 區分不同的操作類型  String method = request.getParameter("method");  if ("upload".equals(method)) {   // 上傳   upload(request,response);  }  else if ("downList".equals(method)) {   // 進入下載列表   downList(request,response);  }  else if ("down".equals(method)) {   // 下載   down(request,response);  } } /**  * 1. 上傳  */ private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  try {   // 1. 建立工廠對象   FileItemFactory factory = new DiskFileItemFactory();   // 2. 檔案上傳核心工具類   ServletFileUpload upload = new ServletFileUpload(factory);   // 設定大小限制參數   upload.setFileSizeMax(10*1024*1024); // 單個檔案大小限制   upload.setSizeMax(50*1024*1024);  // 總檔案大小限制   upload.setHeaderEncoding("UTF-8");  // 對中文檔案編碼處理   // 判斷   if (upload.isMultipartContent(request)) {    // 3. 把請求資料轉換為list集合    List<FileItem> list = upload.parseRequest(request);    // 遍曆    for (FileItem item : list){     // 判斷:普通文本資料     if (item.isFormField()){      // 擷取名稱      String name = item.getFieldName();      // 擷取值      String value = item.getString();      System.out.println(value);     }      // 檔案表單項     else {      /******** 檔案上傳 ***********/      // a. 擷取檔案名稱      String name = item.getName();      // ----處理上傳檔案名稱重名問題----      // a1. 先得到唯一標記      String id = UUID.randomUUID().toString();      // a2. 拼接檔案名稱      name = id + "#" + name;            // b. 得到上傳目錄      String basePath = getServletContext().getRealPath("/upload");      // c. 建立要上傳的檔案對象      File file = new File(basePath,name);      // d. 上傳      item.write(file);      item.delete(); // 刪除群組件運行時產生的臨時檔案     }    }   }  } catch (Exception e) {   e.printStackTrace();  } } /**  * 2. 進入下載列表  */ private void downList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  // 實現思路:先擷取upload目錄下所有檔案的檔案名稱,再儲存;跳轉到down.jsp列表展示  //1. 初始化map集合Map<包含唯一標記的檔案名稱, 簡短檔案名稱> ;  Map<String,String> fileNames = new HashMap<String,String>();  //2. 擷取上傳目錄,及其下所有的檔案的檔案名稱  String bathPath = getServletContext().getRealPath("/upload");  // 目錄  File file = new File(bathPath);  // 目錄下,所有檔案名稱  String list[] = file.list();  // 遍曆,封裝  if (list != null && list.length > 0){   for (int i=0; i<list.length; i++){    // 全名    String fileName = list[i];    // 短名    String shortName = fileName.substring(fileName.lastIndexOf("#")+1);    // 封裝    fileNames.put(fileName, shortName);   }  }  // 3. 儲存到request域  request.setAttribute("fileNames", fileNames);  // 4. 轉寄  request.getRequestDispatcher("/downlist.jsp").forward(request, response); } /**  * 3. 處理下載  */ private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  // 擷取使用者下載的檔案名稱(url地址後追加資料,get)  String fileName = request.getParameter("fileName");  fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");  // 先擷取上傳目錄路徑  String basePath = getServletContext().getRealPath("/upload");  // 擷取一個檔案流  InputStream in = new FileInputStream(new File(basePath,fileName));  // 如果檔案名稱是中文,需要進行url編碼  fileName = URLEncoder.encode(fileName, "UTF-8");  // 設定下載的回應標頭  response.setHeader("content-disposition", "attachment;fileName=" + fileName);  // 擷取response位元組流  OutputStream out = response.getOutputStream();  byte[] b = new byte[1024];  int len = -1;  while ((len = in.read(b)) != -1){   out.write(b, 0, len);  }  // 關閉  out.close();  in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  this.doGet(request, response); }}

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.