首页 > 代码库 > 利用bootsrap控件 实现文件上传功能

利用bootsrap控件 实现文件上传功能

一、jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ page buffer="16kb"%>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 <!DOCTYPE html>
 8 <html lang="en">
 9 <head>
10 <meta charset="UTF-8" />
11 <title>Data file input</title>
12 <link
13     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
14     rel="stylesheet">
15 <link href="http://www.mamicode.com/css/uploadFile/fileinput.css" media="all" rel="stylesheet"
16     type="text/css" />
17 <link href="http://www.mamicode.com/themes/uploadFile/explorer/theme.css" media="all"
18     rel="stylesheet" type="text/css" />
19 <script
20     src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
21 <script src="http://www.mamicode.com/js/uploadFile/plugins/sortable.js" type="text/javascript"></script>
22 <script src="http://www.mamicode.com/js/uploadFile/fileinput.js" type="text/javascript"></script>
23 <script src="http://www.mamicode.com/js/uploadFile/fileinput_locale_fr.js"
24     type="text/javascript"></script>
25 <script src="http://www.mamicode.com/js/uploadFile/fileinput_locale_es.js"
26     type="text/javascript"></script>
27 <script src="http://www.mamicode.com/themes/uploadFile/explorer/theme.js" type="text/javascript"></script>
28 <script
29     src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
30     type="text/javascript"></script>
31 <script type="text/javascript">
32 
33 </script>
34 </head>
35 <body>
36     <div class="container kv-main">
37         <div class="page-header">
38             <h1>Data File Input</h1>
39         </div>
40 
41         <form id="uploadfileform" method="post" action="uploadFile"
42             enctype=multipart/form-data>
43 
44             <div class="form-group">
45                 <input id="file" type="file" name="file" class="file"
46                     data-upload-url="#">
47             </div>
48 
49             <div class="form-group">
50                 <button class="btn btn-warning" type="button">Disable Test</button>
51                 <button class="btn btn-info" type="reset">Refresh Test</button>
52                 <!--   <button class="btn btn-primary" type="button" onclick=" judgeUpload();">Submit</button>-->
53                 <button class="btn btn-primary" type="submit">Submit</button>
54                 <button class="btn btn-default" type="reset">Reset</button>
55             </div>
56 
57         </form>
58         <br>
59     </div>
60 </body>
61 <script type="text/javascript">
62 $(function () {
63     //0.初始化fileinput
64     var oFileInput = new FileInput();
65     oFileInput.Init("file", "/uploadFile");  //file为文件控件的id,uploadFile为后台接受上传文件的servlet
66 });
67 var FileInput = function () {
68     var oFile = new Object();
69     //初始化fileinput控件(第一次初始化)
70     oFile.Init = function(ctrlName, uploadUrl) {
71     var control = $(‘#‘ + ctrlName);
72     //初始化上传控件的样式
73     control.fileinput({
74         language: ‘zh‘, //设置语言
75         uploadUrl: ‘/deke.Business/FileUploadServlet‘, //上传的地址即后台接受上传文件的servlet.
76         allowedFileExtensions: [‘csv‘, ‘arff‘],//接收的文件后缀
77         showUpload: true, //是否显示上传按钮
78         showCaption: false,//是否显示标题
79         browseClass: "btn btn-primary", //按钮样式     
80         maxFileCount: 10, //表示允许同时上传的最大文件个数
81         enctype: ‘multipart/form-data‘,
82         validateInitialCount:true,
83         previewFileIcon: "<i class=‘glyphicon glyphicon-king‘></i>",
84         msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
85     });
86     //导入文件上传完成之后的事件
87     $("#file").on("fileuploaded", function (event, data, previewId, index) {
88         alert("上传成功");
89     });
90 }
91     return oFile;
92 };
93 </script>
94 </html>

 

注意事项:

1.引入bootstrap中的控件。

在该jsp页面中引入的js和css中最基本的两个控件是

bootstrap-fileinput/css/fileinput.min.css

bootstrap-fileinput/js/fileinput.min.js

其他的都是辅助样式。

2.两行关键代码:

<form id="uploadfileform" method="post" action="uploadFile" enctype=multipart/form-data> 
表单提交中的编码格式必须指定为 enctype=multipart/form-data 。
<input id="file" type="file" name="file" class="file" data-upload-url="#">
id="file" :在jsp页面最后的提交表单的js函数中会用到。上述代码中的65行和85行。
data-upload-url="#":这句代码删除之后,页面内的拖拽文件上传的布局会消失。(还不太清楚为什么。)

3.重要的JS初始化

1
上述代码61-92行中的js脚本是用来初始化fileinput控件。
其中最重要的是要指定文件上传的url(65行和75行),即文件要交给哪个servlet来处理。否则即使在表单中指定了action,后台也是无法接收到上传的文件。

2.fileinput()方法里面传入的是一个json数据,它里面有很多属性,每个属性代表着初始化上传控件的时候的特性。
如果这些属性都不设置,则表示使用默认的设置。

可以打开fileinput.js的源码,如图:

技术分享


二、后台代码

 1 package deke.Business;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.io.PrintWriter;
 6 import java.util.List;
 7 
 8 import javax.servlet.RequestDispatcher;
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14 
15 import org.apache.commons.fileupload.FileItem;
16 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
17 import org.apache.commons.fileupload.FileUploadException;
18 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
19 import org.apache.commons.fileupload.servlet.ServletFileUpload;
20 
21 public class FileUploadServlet extends HttpServlet {
22 
23     private static final long serialVersionUID = 1L;
24 
25     // location to store file uploaded
26     private static final String UPLOAD_DIRECTORY = "upload";
27 
28     // upload settings
29     private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3; 
30     private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; 
31     private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; 
32 
33     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34         response.setCharacterEncoding("GBK");
35         PrintWriter out = response.getWriter();
36         if (!ServletFileUpload.isMultipartContent(request)) {
37             out.println("Error: Form must has enctype=multipart/form-data.");
38             out.flush();
39             return;
40         }
41 
42         DiskFileItemFactory factory = new DiskFileItemFactory();
43         factory.setSizeThreshold(MEMORY_THRESHOLD);
44         factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
45 
46         ServletFileUpload upload = new ServletFileUpload(factory);
47         upload.setFileSizeMax(MAX_FILE_SIZE);
48         upload.setSizeMax(MAX_REQUEST_SIZE);
49         String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
50         File uploadDir = new File(uploadPath);
51         if (!uploadDir.exists()) {
52             uploadDir.mkdir();
53         }
54         List<FileItem> formItems = null;
55         try {
56             formItems = upload.parseRequest(request);
57             if(formItems == null || formItems.size() == 0) {
58                 response.sendRedirect("main.jsp");
59                 return;
60             }
61 
62             for (FileItem item : formItems) {
63                 if (!item.isFormField()) {
64                     String fileName = new File(item.getName()).getName();
65                     String filePath = uploadPath + File.separator + fileName;
66                     File storeFile = new File(filePath);
67                     item.write(storeFile);
68                     HttpSession mysession = request.getSession();
69                     mysession.setAttribute("fileName", fileName);
70                     mysession.setAttribute("filePath", filePath);
71                     mysession.setAttribute("uploadFile", storeFile);
72                 }
73             }
74 
75         } catch (FileUploadException e) {
76             if (e instanceof SizeLimitExceededException) {
77                 out.print("<script>alert(‘文件上传超过最大限制:" + MAX_FILE_SIZE + "瀛楄妭‘);history.back();</script>"); 
78                 return;
79             }
80         } catch (Exception e) {
81             e.printStackTrace();
82         }
83 
84         request.getRequestDispatcher("/main.jsp").forward(request,response);
85     }
86 }

 

利用bootsrap控件 实现文件上传功能