拖拽文件上传系统
2016-04-26 16:11
260 查看
html 页面代码
后台servlet处理
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ include file="/includes/ctx.jsp" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>java 开发拖拽文件上传系统</title> <script type="text/javascript" src="${ctx}/js/jquery-1.11.2.js" ></script> <style type="text/css"> *{margin:0;padding:0;} body{font-size:12px;font-family:"微软雅黑";color:#666} img{border:0;} .upload{width:800px;height:240px;margin:50px auto;} .upload .u_logo{text-align:center} .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;} .pic{width:840px;height:300px;margin:0 auto;} .pic ul li {color:#fff;list-style:none;float:left;margin:0 3px 3px 3px;} .pic ul li a:hover img{-webkit-transform:scale(1.5)} </style> </head> <body> <div class="upload"> <div class="u_logo"> </div> <div class="u_box" id="drop_area"> 将文件拖拽到此处 </div> </div> <div class="pic"> <ul> </ul> </div> <script type="text/javascript" > $().ready(function(){ /* $('#dtb-msg1 .compatible').show(); $('#dtb-msg1 .notcompatible').hide(); $('#drop_zone_home').hover(function(){ $(this).children('p').stop().animate({top:'0px'},200); },function(){ $(this).children('p').stop().animate({top:'-44px'},200); }); */ //功能实现 $(document).on({ dragleave:function(e){ e.preventDefault(); //$('.dashboard_target_box').removeClass('over'); $("#drop_area").removeClass("over"); }, drop:function(e){ e.preventDefault(); //$('.dashboard_target_box').removeClass('over'); }, dragenter:function(e){ e.preventDefault(); //$('.dashboard_target_box').addClass('over'); $("#drop_area").addClass("over"); }, dragover:function(e){ e.preventDefault(); //$('.dashboard_target_box').addClass('over'); $("#drop_area").addClass("over"); } }); var box = document.getElementById('drop_area'); box.addEventListener("drop",function(e){ e.preventDefault(); //获取文件列表 var fileList = e.dataTransfer.files; var img = document.createElement('img'); document.body.appendChild(img); //检测是否是拖拽文件到页面的操作 if(fileList.length == 0){ $('.dashboard_target_box').removeClass('over'); return; } alert("获取的长度为"+fileList.length); //检测文件是不是图片 alert(fileList[0].type); alert(fileList[0].type.indexOf('image')); /* if(fileList[0].type.indexOf('image') == -1){ $('.dashboard_target_box').removeClass('over'); return; } */ alert("开始上传"+fileList[0].name); //实例化file reader对象 var reader = new FileReader(); reader.onload = function(e){ img.src = e.target.result; }; reader.readAsDataURL(fileList[0]); /* if($.browser.safari){ //Chrome8+ alert("Chrome8"); img.src = window.webkitURL.createObjectURL(fileList[0]); }else if($.browser.mozilla){ //FF4+ alert("ff4"); img.src = window.URL.createObjectURL(fileList[0]); }else{ alert("else"); //实例化file reader对象 var reader = new FileReader(); reader.onload = function(e){ img.src = this.result; $(document.body).appendChild(img); }; reader.readAsDataURL(fileList[0]); } */ return ; var xhr = new XMLHttpRequest(); xhr.open("post", "${ctx}//upload.do", true); //告诉服务器是以个Ajax 请求 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); var fd = new FormData(); fd.append("doc",fileList[0]); fd.append("doc",fileList[1]); fd.append("name","zfy"); xhr.send(fd); },false); }); </script> </body> </html>
后台servlet处理
package com; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.List; 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; /** * Servlet implementation class UploadServlet */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("进入上传的servlet"); // 获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 获取文件需要上传到的路径 // String path = request.getRealPath("/upload"); String path = "d:/shangchuan/"; // 如果文件夹不存在 将创建文件夹 if (!new File(path).exists()) { new File(path).mkdirs(); } // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存, // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同 /** * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem * 格式的 然后再将其真正写到 对应目录的硬盘上 */ factory.setRepository(new File(path)); // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室 factory.setSizeThreshold(1024 * 1024); // 高水平的API文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory); try { // 可以上传多个文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 获取表单的属性名字 String name = item.getFieldName(); // 如果获取的 表单信息是普通的 文本 信息 if (item.isFormField()) { // 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的 String value = item.getString(); System.out.println("name:" + name); System.out.println("value:" + value); request.setAttribute(name, value); } // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些 else { /** * 以下三步,主要获取 上传文件的名字 */ // 获取路径名 String value = item.getName(); // 索引到最后一个反斜杠 int start = value.lastIndexOf("\\"); // 截取 上传文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start + 1); // 将当前时间戳 作为的文件名 String newfilename = Long.toString(new Date().getTime()) + filename.substring(filename.indexOf('.')); request.setAttribute(name, newfilename); // 真正写到磁盘上 // 它抛出的异常 用exception 捕捉 // item.write( new File(path,filename) );//第三方提供的 // 手动写的 OutputStream out = new FileOutputStream(new File(path, newfilename)); InputStream in = item.getInputStream(); int length = 0; byte[] buf = new byte[1024]; System.out.println("获取上传文件的总共的容量:" + item.getSize()); // in.read(buf) 每次读到的数据存放在 buf 数组中 while ((length = in.read(buf)) != -1) { // 在 buf 数组中 取出数据 写到 (输出流)磁盘上 out.write(buf, 0, length); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("走到最后"); } }
相关文章推荐
- [问题] UISearchBar 点击取消后跳动的问题[转载]
- SDUSTOJ 1795 哆啦A梦的程序(思路题)
- CodeForces 558D
- 运行时异常与一般异常有何异同
- Studio打包签名
- 设置UIButton的Title在左,Image在右
- iOS集成极光推送
- c++对内存的浅谈以及内存泄漏问题的探讨之九
- php正则提取html图片(img)src地址与任意属性
- quartz定时任务时间设置
- 不影响数据库运行如何快速恢复刚删除的表及其数据(一)flashback是什么
- quartz定时任务时间设置
- range小数
- for range
- 百度地图根据经纬度获取地址/根据地获取经纬度
- iOS- 利用AFNetworking(AFN) - 实现图片上传
- Silverlight DataGrid 绑定的多选、全选
- 剑指Offer--029-数组中出现次数超过一半的数字
- iOS瀑布流
- Android带渐变效果的圆角矩形Demo