(1)index.htmlcss
<!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <link rel="stylesheet" href="./layui/css/layui.css" media="all"> </head> <body> <div class="layui-container"> <form class="layui-form" action="" enctype="multipart/form-data"> <div class="layui-form-item"> <label class="layui-form-label">標題</label> <div class="layui-input-block"> <input id="title" type="text" name="title" maxlength="300" required lay-verify="required" placeholder="請輸入標題" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">上傳文件</label> <div class="layui-input-inline uploadHeadImage"> <div class="layui-upload-drag" id="uploadFile"> <i class="layui-icon"></i> <p>點擊上傳文件,或將文件拖拽到此處!</p> </div> </div> <div class="layui-input-inline"> <div id="uploadResult" class="layui-upload-list"> </div> </div> </div> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">備註</label> <div class="layui-input-block"> <textarea name="desc" placeholder="請輸入內容" maxlength="1000" class="layui-textarea"></textarea> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" id="uploadBtn">提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </body> <script src="./jquery/jquery.min.js"></script> <script src="./layui/layui.js"></script> <script> layui.use('upload', function() { var upload = layui.upload; //執行上傳 var uploadInst = upload.render({ elem: '#uploadFile', //綁定元素 url: '../FileUploadServer', //上傳接口 method: 'POST', auto: false, accept: 'file', bindAction: '#uploadBtn', size: 10240,//限制文件大小10M multiple: false, data:{}, before: function(obj) { layer.load(); this.data.title = $('#title').val(); }, done: function(data, index, upload) {//上傳完畢回調 layer.closeAll('loading'); if (data.no === 1) { layer.msg("上傳成功!", { icon: 6 }); } else { layer.msg("上傳失敗,請稍後重試!", { icon: 5 }); } var uuid = data.uuid; $("#uploadResult").append('<input readonly type="text" value="'+uuid+'" class="layui-input" />'); } , error: function() {//請求異常回調 layer.closeAll('loading'); layer.msg('網絡異常,請稍後重試!'); } }); }); </script> </html>
(2)後臺服務html
package com.microwisdom.file; import com.google.gson.Gson; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * @做者 yan * @建立日期 * @版本 V1.0 * @描述 * @Path */ public class FileUploadServer extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter pw = response.getWriter(); Map<String,Object> resultMap = new HashMap<String,Object>(); String result = ""; //上傳文件的保存目錄 String savePath = "D:\\tmp\\file_server\\app\\"; //上傳時生成的臨時文件保存目錄 String tempPath = "D:\\tmp\\file_server\\tmp"; File tmpFile = new File(tempPath); if (!tmpFile.exists()) { //建立臨時目錄 tmpFile.mkdir(); } //使用Apache文件上傳組件處理文件上傳步驟: //一、建立一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //設置工廠的緩衝區的大小,當上傳的文件大小超過緩衝區的大小時,就會生成一個臨時文件存放到指定的臨時目錄當中。 factory.setSizeThreshold(1024 * 1024 * 10);//設置緩衝區的大小爲10M,若是不指定,那麼緩衝區的大小默認是10KB //設置上傳時生成的臨時文件的保存目錄 factory.setRepository(tmpFile); //二、建立一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //三、判斷提交上來的數據是不是上傳表單的數據 if (!ServletFileUpload.isMultipartContent(request)) { //按照傳統方式獲取數據 return; } //設置上傳單個文件的大小的最大值,目前是設置爲1024*1024*10字節,也就是10MB upload.setFileSizeMax(1024 * 1024 * 10); //設置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和,目前設置爲10MB upload.setSizeMax(1024 * 1024 * 10); //四、使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個List<FileItem>集合,每個FileItem對應一個Form表單的輸入項 List<FileItem> list = null; try { list = upload.parseRequest(request); for (FileItem item : list) { //若是fileitem中封裝的是普通輸入項的數據 if (item.isFormField()) { String name = item.getFieldName(); //解決普通輸入項的數據的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); } else {//若是fileitem中封裝的是上傳文件 //獲得上傳的文件名稱, String filename = item.getName(); System.out.println(filename); if (filename == null || filename.trim().equals("")) { continue; } //注意:不一樣的瀏覽器提交的文件名是不同的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\") + 1); //獲得上傳文件的擴展名 String fileExtName = filename.substring(filename.lastIndexOf(".") + 1); //若是須要限制上傳的文件類型,那麼能夠經過文件的擴展名來判斷上傳的文件類型是否合法 System.out.println("上傳的文件的擴展名是:" + fileExtName); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //獲得文件保存的名稱 String saveFilename = makeFileName(filename); //獲得文件的保存目錄 String realSavePath = makePath(saveFilename, savePath); //建立一個文件輸出流 FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename); //建立一個緩衝區 byte buffer[] = new byte[1024]; //判斷輸入流中的數據是否已經讀完的標識 int len = 0; //循環將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裏面還有數據 while ((len = in.read(buffer)) > 0) { //使用FileOutputStream輸出流將緩衝區的數據寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close(); //刪除處理文件上傳時生成的臨時文件 item.delete(); resultMap.put("no", 1); resultMap.put("msg", "文件上傳成功!"); resultMap.put("uuid", UUID.randomUUID().toString().replaceAll("-", "")); result = new Gson().toJson(resultMap); } } } catch (FileUploadException ex) { Logger.getLogger(FileUploadServer.class.getName()).log(Level.SEVERE, null, ex); } finally{ pw.print(result); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } private String makeFileName(String filename){ //爲防止文件覆蓋的現象發生,要爲上傳文件產生一個惟一的文件名 return UUID.randomUUID().toString() + "_" + filename; } private String makePath(String filename,String savePath){ //獲得文件名的hashCode的值,獲得的就是filename這個字符串對象在內存中的地址 int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 //構造新的保存目錄 String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 //File既能夠表明文件也能夠表明目錄 File file = new File(dir); //若是目錄不存在 if(!file.exists()){ //建立目錄 file.mkdirs(); } return dir; } }