拖拽文件上传系统

html 页面代码

  1 <%@ page language="java" contentType="text/html; charset=utf-8"
  2     pageEncoding="utf-8"%>
  3     <%@ include file="/includes/ctx.jsp" %>
  4 <!DOCTYPE html>
  5 <html>
  6 <head>
  7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  8 <title>java 开发拖拽文件上传系统</title>
  9 
 10     <script type="text/javascript" src="${ctx}/js/jquery-1.11.2.js" ></script>
 11 
 12     <style type="text/css">
 13         *{margin:0;padding:0;}
 14         body{font-size:12px;font-family:"微软雅黑";color:#666}
 15         img{border:0;}
 16         .upload{width:800px;height:240px;margin:50px auto;}
 17         .upload .u_logo{text-align:center}
 18         .upload .u_box{width:640px;height:130px;border:3px dashed #E6E6E6;margin:0 auto; font-size:36px;color:#D1D1D1;text-align:center;line-height:130px;}
 19         
 20         .pic{width:840px;height:300px;margin:0 auto;}
 21         .pic ul li {color:#fff;list-style:none;float:left;margin:0 3px 3px 3px;}
 22         .pic ul li a:hover img{-webkit-transform:scale(1.5)}
 23         
 24     </style>
 25 </head>
 26 <body>
 27     <div class="upload">
 28         <div class="u_logo">
 29         </div>
 30         <div class="u_box" id="drop_area">
 31             将文件拖拽到此处
 32         </div>
 33     </div>
 34     <div class="pic">
 35         <ul>
 36         </ul>
 37     </div>
 38 
 39 <script type="text/javascript" >
 40         
 41         $().ready(function(){
 42                 /* $('#dtb-msg1 .compatible').show();
 43                 $('#dtb-msg1 .notcompatible').hide();
 44                 $('#drop_zone_home').hover(function(){
 45                     $(this).children('p').stop().animate({top:'0px'},200);
 46                 },function(){
 47                     $(this).children('p').stop().animate({top:'-44px'},200);
 48                 }); */
 49                 //功能实现
 50                 $(document).on({
 51                     dragleave:function(e){
 52                         e.preventDefault();
 53                         //$('.dashboard_target_box').removeClass('over');
 54                         $("#drop_area").removeClass("over");
 55                     },
 56                     drop:function(e){
 57                         e.preventDefault();
 58                         //$('.dashboard_target_box').removeClass('over');
 59                     },
 60                     dragenter:function(e){
 61                         e.preventDefault();
 62                         //$('.dashboard_target_box').addClass('over');
 63                         $("#drop_area").addClass("over");
 64                     },
 65                     dragover:function(e){
 66                         e.preventDefault();
 67                         //$('.dashboard_target_box').addClass('over');
 68                         $("#drop_area").addClass("over");
 69                     }
 70                 });
 71                 var box = document.getElementById('drop_area');
 72                 box.addEventListener("drop",function(e){
 73                     e.preventDefault();
 74                     //获取文件列表
 75                     var fileList = e.dataTransfer.files;
 76                     var img = document.createElement('img');
 77                     document.body.appendChild(img);
 78                     
 79                     //检测是否是拖拽文件到页面的操作
 80                     if(fileList.length == 0){
 81                         $('.dashboard_target_box').removeClass('over');
 82                         return;
 83                     }
 84                     alert("获取的长度为"+fileList.length);
 85                     //检测文件是不是图片
 86                     alert(fileList[0].type);
 87                     alert(fileList[0].type.indexOf('image'));
 88                     /* if(fileList[0].type.indexOf('image') == -1){
 89                         $('.dashboard_target_box').removeClass('over');
 90                         return;
 91                     } */
 92                     
 93                     alert("开始上传"+fileList[0].name);
 94                     //实例化file reader对象
 95                     var reader = new FileReader();
 96                     reader.onload = function(e){
 97                         img.src = e.target.result;
 98                     };
 99                     reader.readAsDataURL(fileList[0]);
100                     
101                      /* if($.browser.safari){
102                         //Chrome8+
103                         alert("Chrome8");
104                         img.src = window.webkitURL.createObjectURL(fileList[0]);
105                     }else if($.browser.mozilla){
106                         //FF4+
107                         alert("ff4");
108                         img.src = window.URL.createObjectURL(fileList[0]);
109                     }else{
110                         alert("else");
111                         //实例化file reader对象
112                         var reader = new FileReader();
113                         reader.onload = function(e){
114                             img.src = this.result;
115                             $(document.body).appendChild(img);
116                         };
117                         reader.readAsDataURL(fileList[0]);
118                     }  */
119                     return ;
120                     var xhr = new XMLHttpRequest();
121                     xhr.open("post", "${ctx}//upload.do", true);
122                     //告诉服务器是以个Ajax 请求
123                     xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
124                     
125                     var fd = new FormData();
126                     fd.append("doc",fileList[0]);
127                     fd.append("doc",fileList[1]);
128                     fd.append("name","zfy");
129                     xhr.send(fd);
130                 },false);
131         });
132         
133     </script>
134 </body>
135 </html>

后台servlet处理

  1 package com;
  2 
  3 import java.io.File;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.OutputStream;
  8 import java.util.Date;
  9 import java.util.List;
 10 
 11 import javax.servlet.ServletException;
 12 import javax.servlet.http.HttpServlet;
 13 import javax.servlet.http.HttpServletRequest;
 14 import javax.servlet.http.HttpServletResponse;
 15 
 16 import org.apache.commons.fileupload.FileItem;
 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 /**
 22  * Servlet implementation class UploadServlet
 23  */
 24 public class UploadServlet extends HttpServlet {
 25     private static final long serialVersionUID = 1L;
 26 
 27     /**
 28      * @see HttpServlet#HttpServlet()
 29      */
 30     public UploadServlet() {
 31         super();
 32     }
 33 
 34     /**
 35      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 36      *      response)
 37      */
 38     protected void doGet(HttpServletRequest request,
 39             HttpServletResponse response) throws ServletException, IOException {
 40         doPost(request, response);
 41     }
 42 
 43     /**
 44      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 45      *      response)
 46      */
 47     protected void doPost(HttpServletRequest request,
 48             HttpServletResponse response) throws ServletException, IOException {
 49         // TODO Auto-generated method stub
 50         System.out.println("进入上传的servlet");
 51 
 52         // 获得磁盘文件条目工厂
 53         DiskFileItemFactory factory = new DiskFileItemFactory();
 54         // 获取文件需要上传到的路径
 55         // String path = request.getRealPath("/upload");
 56         String path = "d:/shangchuan/";
 57 
 58         // 如果文件夹不存在 将创建文件夹
 59         if (!new File(path).exists()) {
 60             new File(path).mkdirs();
 61         }
 62 
 63         // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
 64         // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
 65         /**
 66          * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
 67          * 格式的 然后再将其真正写到 对应目录的硬盘上
 68          */
 69         factory.setRepository(new File(path));
 70         // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
 71         factory.setSizeThreshold(1024 * 1024);
 72 
 73         // 高水平的API文件上传处理
 74         ServletFileUpload upload = new ServletFileUpload(factory);
 75 
 76         try {
 77             // 可以上传多个文件
 78             List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
 79 
 80             for (FileItem item : list) {
 81                 // 获取表单的属性名字
 82                 String name = item.getFieldName();
 83 
 84                 // 如果获取的 表单信息是普通的 文本 信息
 85                 if (item.isFormField()) {
 86                     // 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
 87                     String value = item.getString();
 88 
 89                     System.out.println("name:" + name);
 90 
 91                     System.out.println("value:" + value);
 92 
 93                     request.setAttribute(name, value);
 94                 }
 95                 // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
 96                 else {
 97                     /**
 98                      * 以下三步,主要获取 上传文件的名字
 99                      */
100                     // 获取路径名
101                     String value = item.getName();
102                     // 索引到最后一个反斜杠
103                     int start = value.lastIndexOf("\");
104                     // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
105                     String filename = value.substring(start + 1);
106                     // 将当前时间戳 作为的文件名
107                     String newfilename = Long.toString(new Date().getTime())
108                             + filename.substring(filename.indexOf('.'));
109                     request.setAttribute(name, newfilename);
110 
111                     // 真正写到磁盘上
112                     // 它抛出的异常 用exception 捕捉
113 
114                     // item.write( new File(path,filename) );//第三方提供的
115 
116                     // 手动写的
117                     OutputStream out = new FileOutputStream(new File(path,
118                             newfilename));
119 
120                     InputStream in = item.getInputStream();
121 
122                     int length = 0;
123                     byte[] buf = new byte[1024];
124 
125                     System.out.println("获取上传文件的总共的容量:" + item.getSize());
126 
127                     // in.read(buf) 每次读到的数据存放在 buf 数组中
128                     while ((length = in.read(buf)) != -1) {
129                         // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
130                         out.write(buf, 0, length);
131 
132                     }
133 
134                     in.close();
135                     out.close();
136                 }
137             }
138 
139         } catch (FileUploadException e) {
140             // TODO Auto-generated catch block
141             e.printStackTrace();
142         } catch (Exception e) {
143             // TODO Auto-generated catch block
144 
145             e.printStackTrace();
146         }
147         System.out.println("走到最后");
148 
149     }
150 
151 }
原文地址:https://www.cnblogs.com/zfy0098/p/5435511.html