多文件上傳artDialog+plupload

1、效果展現

包括文件上傳面板以及文件上傳列表javascript

2、介紹

長話短說,採用spring springMVC mybatis maven mysql,實現多文件上傳功能,下載使用的是流的形式。css

其中涉及的分頁我會另開一片博客介紹。java

3、準備材料

pluploadmysql

artDialogjquery

還有一份初始化插件的js文件spring

這些能夠直接從個人分享鏈接裏面下載sql

連接:http://pan.baidu.com/s/1c27cTAK 密碼:btqj數據庫

還有jquery 這個自行下載mybatis

4、前臺代碼

引入樣式以及js文件app

1 <link rel="stylesheet" href="resources/css/plupload.css" type="text/css">
2 
3 <script src="resources/js/jquery.min.js"></script>
4 <script src="resources/upload/plupload.full.min.js"></script>
5 <script src="resources/artDialog4.1.7/artDialog.source.js?skin=blue"></script>
6 <script src="resources/js/upload.js"></script>

js代碼

 _plupload(綁定的uuid,文件上傳路徑);
①關於綁定的uuid,我舉個例子,當前用戶的id就是uuid,你能夠把用戶id和你上傳的文件相關聯,之後查詢的話根據用戶id就能查詢這個用戶上傳的全部文件
②這個方法是封裝過的,在upload.js裏面能看到,我裏面註釋寫的很清楚,也能夠參考官方文檔
1 $(function() {
2         3         $('#uploadBtn').click(function() {
4             popUpDialog();
5         });
6         _plupload('test','${pageContext.request.contextPath}/uploadfile');
7 
8     });

 頁面代碼,一個按鈕,一個彈出框

1 <a id="uploadBtn" class="optionbtn inline" href="#">文件上傳</a>
2     <!-- 觸發彈出框 -->
3     <div id="uploadContent" style="display: none; height: 300px; overflow-x: hidden; overflow-y: auto;">
4         <div id="choosefile">
5             <span>單個文件支持小於100M</span><br /> <a id="uploadify" href="javascript:void(0);">選擇文件</a>
6         </div>
7         <div id="uploadfileQueue" style="border: 1px solid #a7c5e2; height: 228px; width: 350px;"></div>
8     </div>
9     <pre id="console"></pre>

 

5、後臺代碼

我都沒有封裝成方法,爲了看得明白,能夠本身封裝一下

 1     /**
 2      * 文件上傳請求地址
 3      * 
 4      * @param request
 5      * @param response
 6      */
 7     @RequestMapping("uploadfile")
 8     public void upload(HttpServletRequest request, HttpServletResponse response) {
 9 
10         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;// 二進制上傳
11         CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");// 獲取文件
12 
13         String unid = UUID.randomUUID().toString().replace("-", "");/* 文件主鍵 */
14         String originalFilename = file.getOriginalFilename();/* 原文件名,包括後綴 */
15         String flieSize = String.valueOf(file.getSize());/* 文件大小 */
16         String path = null;/* 文件存儲路徑 */
17         String punid = request.getParameter("punid"); /* 關聯文件punid */
18 
19         // 保存文件
20         if (file != null) {
21             try {
22                 String basePath = request.getSession().getServletContext().getRealPath("/uploadfile");
23                 SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
24                 String subPath = sdf.format(new Date());
25                 path = basePath + subPath + unid + File.separator + originalFilename;
26 
27                 // 若是文件夾不存在,就建立文件夾
28                 File dir = new File(path);
29                 if (!dir.exists()) {
30                     dir.mkdirs();
31                 }
32                 file.transferTo(dir);
33             } catch (Exception e) {
34                 e.printStackTrace();
35             }
36         }
37 
38         // 文件大小轉換
39         long kb = 1024;
40         long mb = kb * 1024;
41         long gb = mb * 1024;
42         long size = Long.parseLong(flieSize);
43         if (size >= gb) {
44             flieSize = String.format("%.1f GB", (float) size / gb);
45         } else if (size >= mb) {
46             float f = (float) size / mb;
47             flieSize = String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
48         } else if (size >= kb) {
49             float f = (float) size / kb;
50             flieSize = String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
51         } else {
52             flieSize = String.format("%d B", size);
53         }
54 
55         // 存儲文件信息進數據庫
56         FileUpload fileUpload = new FileUpload();
57         fileUpload.setUnid(unid);
58         fileUpload.setOriginalFilename(originalFilename);
59         fileUpload.setFlieSize(flieSize);
60         fileUpload.setPath(path);
61         fileUpload.setPunid(punid);
62         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
63         fileUpload.setFlieTime(df.format(new Date()));
64         fileUploadService.insert(fileUpload);
65     }

 這裏附帶一個下載的方法,是用文件流,根據文件id來進行下載

 1     @RequestMapping("downloadfile")
 2     public void downLoadfile(HttpServletRequest request, HttpServletResponse response) {
 3         String unid = request.getParameter("unid");
 4         FileUpload fileUpload = fileUploadService.selectByPrimaryKey(unid);
 5         if (fileUpload != null) {
 6             try {
 7                 String filename = new String(fileUpload.getOriginalFilename().getBytes("GBK"), "ISO-8859-1");
 8                 String path = fileUpload.getPath();
 9                 response.setCharacterEncoding("utf-8");
10                 response.setContentType("application/octet-stream");
11                 response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
12                 response.setHeader("Content-Length", fileUpload.getFlieSize());
13 
14                  InputStream inputStream = new FileInputStream(new
15                  File(path));
16                  OutputStream os = response.getOutputStream();
17                  byte[] b = new byte[2048];
18                  int length;
19                  while ((length = inputStream.read(b)) > 0) {
20                  os.write(b, 0, length);
21                  }
22                  os.close();
23                  inputStream.close();
24             } catch (FileNotFoundException e) {
25                 e.printStackTrace();
26             } catch (IOException e) {
27                 e.printStackTrace();
28             }
29         }
30     }

 

還有一個刪除方法

 1     /**
 2      * 文件刪除
 3      * 
 4      * @param request
 5      * @param response
 6      */
 7     @ResponseBody
 8     @RequestMapping("delfile")
 9     public Map<String, Object> delfile(HttpServletRequest request, HttpServletResponse response) {
10         String unid = request.getParameter("unid");
11         FileUpload fileUpload = fileUploadService.selectByPrimaryKey(unid);
12         // 刪除本地
13         boolean flag = false;
14         File file = new File(fileUpload.getPath());
15         if (file.exists()) {// 路徑爲文件且不爲空則進行刪除
16             flag = file.delete();
17         }
18         // 刪除數據庫
19         int result = fileUploadService.deleteByPrimaryKey(unid);
20         if (result > 0) {
21             flag = true;
22         }
23         Map<String, Object> map = new HashMap<String, Object>();
24         map.put("result", flag);
25         return map;
26     }

 

6、最後

若是要完整的代碼能夠給我留言,我發給你

相關文章
相關標籤/搜索