SmartUpload組件實現文件上傳和下載

java文件上傳下載 使用SmartUpload組件實現

 使用SmartUpload組件實現(下載jsmartcom_zh_CN.jar) 2017-11-07  

1、在WebRoot創建以下文件夾,css存放樣式文件(css文件直接拷貝進去),images存放圖片(圖片也拷貝進去),js存放js文件(拷貝),jsp存放我們的jsp文件

2、創建jsp文件 01.jsp

3、編寫jsp

複製代碼
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 <html>
 8   <head>
 9     <base href="<%=basePath%>">
10     <title>My JSP '01.jsp' starting page</title>
11     <!-- 引入我們css樣式文件 -->
12     <link rel="stylesheet" type="text/css" href="css/common.css">
13     <!-- 引入我們js文件 -->
14     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
15     <script type="text/javascript">
16         /*
17             替換默認顯示圖片,顯示當前我們選中的圖片
18             1、獲取<p class="thumbs">中<a>標籤事件
19             2、獲取href title
20             3、獲取<p><img id="largeImg"</p> 
21             4、把當前選中的href title賦給默認
22         */
23         $(function(){
24             $(".thumbs a").click(function(){
25                 var largePath = $(this).attr("href");
26                 var largeAlt = $(this).attr("title");
27                 $("#largeImg").attr({
28                     src:largePath,
29                     alt:largeAlt
30                 });
31                 return false;
32             });
33         });
34         
35     </script>
36   </head>
37   
38   <body>
39         <h2>文件批量上傳</h2>
40         <!-- 處理類路徑,提交方式,類型 -->
41         <form action="smartUploadServlet.do" method="post" enctype="multipart/form-data">
42             <label>文件一:</label>
43             <input name="myfile1" type="file"/><br>
44             <label>文件二:</label>
45             <input name="myfile2" type="file"/><br>
46             <label>文件三:</label>
47             <input name="myfile3" type="file"/><br>
48             <!-- 處理完後臺返回一個消息同el表達式${result} -->
49             <input type="submit" value="上傳文件"/><b style="color: red">${result}</b>
50         </form>
51         <hr>
52         
53         <h2>文件批量下載</h2>
54         <!-- 處理類路徑 -->
55         <form action="batchDownloadServlet.do">
56             <input type="checkbox" name="filename" value="img2-lg.jpg"/>Image2
57             <input type="checkbox" name="filename" value="img3-lg.jpg"/>Image3
58             <input type="checkbox" name="filename" value="img4-lg.jpg"/>Image4
59             <input type="submit" value="下載文件"/>
60         </form>
      <!--
下載:<input type="file" name="filename" value="img2-lg.jpg"/>Image2
   --> 61 <hr> 62 63 <h2>圖片預覽</h2> 64 <p><img id="largeImg" alt="Large Image" src="images/img1-lg.jpg"></p> 65 <p class="thumbs"> 66 <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a> 67 <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a> 68 <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a> 69 <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a> 70 <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a> 71 </p> 72 </body> 73 </html>
複製代碼

4、後臺創建SmartUploadServlet(上傳)   web.xml配置路徑,jsp文件中<form action="smartUploadServlet.do">必須和web.xml中一致

複製代碼
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3 xmlns="http://java.sun.com/xml/ns/javaee" 
 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 5   <display-name>scx</display-name>
 6   
 7   <servlet>
 8     <servlet-name>SmartUploadServlet</servlet-name>
 9     <servlet-class>com.imooc.servlet.SmartUploadServlet</servlet-class>
10   </servlet>
11   
12   <servlet>
13     <servlet-name>SmartDownloadServlet</servlet-name>
14     <servlet-class>com.imooc.servlet.SmartDownloadServlet</servlet-class>
15   </servlet>
16   <servlet>
17     <servlet-name>BatchDownloadServlet</servlet-name>
18     <servlet-class>com.imooc.servlet.BatchDownloadServlet</servlet-class>
19   </servlet>
20 
21   <servlet-mapping>
22     <servlet-name>SmartUploadServlet</servlet-name>
23     <url-pattern>/smartUploadServlet.do</url-pattern>
24   </servlet-mapping>
25   
26   <servlet-mapping>
27     <servlet-name>SmartDownloadServlet</servlet-name>
28     <url-pattern>/smartDownloadServlet.do</url-pattern>
29   </servlet-mapping>
30   
31   <servlet-mapping>
32     <servlet-name>BatchDownloadServlet</servlet-name>
33     <url-pattern>/batchDownloadServlet.do</url-pattern>
34   </servlet-mapping>
35   
36   <welcome-file-list>
37     <welcome-file>index.jsp</welcome-file>
38   </welcome-file-list>
39 </web-app>
複製代碼

 

5、編寫SmartUploadServlet(多個上傳,單個上傳只需要把jsp文件中input留下一個)

複製代碼
 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.jspsmart.upload.SmartUpload;
12 
13 public class SmartUploadServlet extends HttpServlet {
14 
15     /**
16      * 
17      */
18     private static final long serialVersionUID = 1L;
19 
20     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21         doPost(req, resp);
22     }
23 
24     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
25 
26         req.setCharacterEncoding("UTF-8");
27         // 設置上傳的保存路徑
28         String filePath = getServletContext().getRealPath("/") + "images";
29         // 創建文件對象 如果存在就不創建,否則創建文件夾
30         File file = new File(filePath);
31         if (file.exists()) {
32             file.mkdir();
33         }
34         // 創建SmartUpload對象
35         SmartUpload su = new SmartUpload();
36         // 初始化對象
37         su.initialize(getServletConfig(), req, resp);
38         // 設置上傳文件大小
39         su.setTotalMaxFileSize(1024 * 1024 * 100);
40         // 設置上傳文件類型
41         su.setAllowedFilesList("txt,jpg,gif");
42         // 創建提示變量
43         String result = "上傳成功";
44         try {
45             // 設置禁止上傳類型
46             su.setDeniedFilesList("rar,jsp,js");
47             su.upload();
48             // 返回上傳文件數量
49             int count = su.save(filePath);
50             System.out.println("上傳成功" + count + "個文件!");
51 
52         } catch (Exception e) {
53             result = "上傳失敗";
54             e.printStackTrace();
55         }
56 
57         // 獲取上傳成功的文件的屬性
58         for (int i = 0; i < su.getFiles().getCount(); i++) {
59             com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
60             System.out.println("---------------------");
61             System.out.println("表單當中name屬性值:" + tempFile.getFieldName());
62             System.out.println("上傳文件名:" + tempFile.getFieldName());
63             System.out.println("上傳文件長度:" + tempFile.getSize());
64             System.out.println("上傳文件的拓展名:" + tempFile.getFileExt());
65             System.out.println("上傳文件的全名:" + tempFile.getFilePathName());
66             System.out.println("---------------------");
67         }
68         req.setAttribute("result", result);
69         req.getRequestDispatcher("jsp/01.jsp").forward(req, resp);
70     }
71 
72 }

6、SmartDownloadServlet(單個下載)
複製代碼
 1 package com.imooc.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.jspsmart.upload.SmartUpload;
11 import com.jspsmart.upload.SmartUploadException;
12 
13 public class SmartDownloadServlet extends HttpServlet {
14 
15     /**
16      * 
17      */
18     private static final long serialVersionUID = 1L;
19 
20     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         doPost(request, response);
22     }
23 
24     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
25         // 獲取文件名稱
26         String filename = request.getParameter("filename");
27         SmartUpload su = new SmartUpload();
28         // 初始化
29         su.initialize(getServletConfig(), request, response);
30         // 把默認顯示方式設爲空
31         su.setContentDisposition(null);
32 
33         try {
34             su.downloadFile("/images/" + filename);
35         } catch (SmartUploadException e) {
36             e.printStackTrace();
37         }
38     }
39 }
7、BatchDownloadServlet(多個文件下載)
複製代碼
 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.util.zip.ZipEntry;
 7 import java.util.zip.ZipOutputStream;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 public class BatchDownloadServlet extends HttpServlet {
15 
16     /**
17      * 
18      */
19     private static final long serialVersionUID = 1L;
20 
21     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
22         doPost(req, resp);
23     }
24 
25     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
26         resp.setContentType("application/x-msdownload");
27         // 以附件的形式下載
28         resp.setHeader("Content-Disposition", "attachment;filename=test.zip");
29 
30         // 獲取下載路徑
31         String path = getServletContext().getRealPath("/") + "images/";
32         // 獲取文件數組
33         String[] filenames = req.getParameterValues("filename");
34         // 創建空字符串
35         String str = "";
36         // 換行符
37         String rt = "\r\n";
38         // 創建壓縮包輸出流
39         ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
40         // 遍歷文件數組
41         for (String filename : filenames) {
42             str += filename + rt;
43             // 創建文件對象
44             File file = new File(path + filename);
45             zos.putNextEntry(new ZipEntry(filename));
46             // 創建文件輸出流
47             FileInputStream fis = new FileInputStream(file);
48             byte[] b = new byte[1024];
49             int n = 0;
50             while ((n = fis.read(b)) != -1) {
51                 zos.write(b, 0, n);
52             }
53             zos.flush();
54             fis.close();
55         }
56         zos.setComment("成功" + rt + str);
57         zos.flush();
58         zos.close();
59     }
60 }

效果圖
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章