调用html 5接口实现断点上传文件

4 篇文章 0 订阅
1 篇文章 0 订阅

1 、java端使用servlet 接受请求

package com.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

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;
import org.apache.commons.io.IOUtils;

/**
 * 
 * @author gjl
 * 文件上传
 * 具体步骤:
 * 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包
 * 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同
 * 3)对 DiskFileItemFactory 对象设置一些 属性
 * 4)高水平的API文件上传处理  ServletFileUpload upload = new ServletFileUpload(factory);
 * 目的是调用 parseRequest(request)方法  获得 FileItem 集合list ,
 *     
 * 5)在 FileItem 对象中 获取信息,   遍历, 判断 表单提交过来的信息 是否是 普通文本信息  另做处理
 * 6)
 *    第一种. 用第三方 提供的  item.write( new File(path,filename) );  直接写到磁盘上
 *    第二种. 手动处理  
 *
 */
@MultipartConfig
public class AjaxFilesUploadServlet extends HttpServlet
{
    
    /**
     * 注释内容
     */
    private static final long serialVersionUID = 513258132164002370L;
    
    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        String fileStr = new String(request.getParameter("filename")
                .getBytes("ISO-8859-1"), "utf-8"); //中文乱码
        
        String files[] = fileStr.split(","); //多个文件
        
        //获取文件需要上传到的路径
        String path = request.getRealPath("/upload") + File.separator;
        JSONObject json = new JSONObject();
        json.put("succ", true);
        JSONObject jo = new JSONObject();
        for (int i = 0; i < files.length; i++)
        {
            String[] file = files[i].split("\\!");
            String id = file[0];
            String fileRef = file[1];
            String name = fileRef.substring(0, fileRef.lastIndexOf("."));
            String type = fileRef.substring(fileRef.lastIndexOf(".") + 1);
            
            long size = getFileSize(path + name + "." + type);
            
            jo.put(id, size);
            json.put("data", jo);
        }
        System.out.println("get返回json数据:" + json);
        
        response.setContentType("text/plain");
        response.getWriter().write(json.toString());
        
    }
    
    /** <一句话功能简述>
     * 根据文件路径取得文件大小
     * @param filePath 文件路径
     * @return 返回文件大小
     * 
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private long getFileSize(String filePath)
    {
        long size = 0;
        File file = new File(filePath);
        if (file.exists())
        {
            
            size = file.length();
            
        }
        
        return size;
    }
    
    /**
     * 上传流文件并保存
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        
        request.setCharacterEncoding("utf-8"); //设置编码
        System.out.println("开始访问servlet(dopost) :");
        
        JSONObject json = new JSONObject(); //返回的json串
        
        String filename = ""; //文件名称
        String path = request.getRealPath("/upload"); //获取文件需要上传到的路径
        
        try
        {
            List<FileItem> items = new ServletFileUpload(
                    new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items)
            {
                if (item.isFormField())
                {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = "";
                    if (fieldname.equals("name"))
                    {
                        filename = fieldvalue = URLDecoder.decode(item.getString(),
                                "UTF-8");
                        
                    }
                    else
                    {
                        fieldvalue = item.getString();
                    }
                    
                    System.out.println("fieldname:" + fieldname
                            + "--fieldvalue:" + fieldvalue);
                    // ... (do your job here)
                }
                else
                {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    //String filename = FilenameUtils.getName(item.getName());
                    InputStream filecontent = item.getInputStream();
                    System.out.println("fieldname:" + fieldname + "--filename:"
                            + filename + "---filecontent:" + filecontent
                            + "---path:" + path);
                    // item.write( new File(path,filename) );//第三方提供的;
                    //手动写入硬盘
                    if (makeDir(path))
                    {
                        createFile(path, filename);
                    }
                    
                    File file = new File(path + File.separator + filename);
                    FileOutputStream fos = new FileOutputStream(file, true);
                    InputStream is = item.getInputStream();
                    IOUtils.copy(is, fos);
                    is.close();
                    fos.close();
                    
                    System.out.println("获取上传文件的总共的容量:" + item.getSize());
                }
            }
        }
        catch (FileUploadException e)
        {
            e.printStackTrace();
        }
        /** 前端参数 **/
        //		String filenameaaa = request.getParameter("name");
        //	    String fileid = request.getParameter("fileid");
        //	    String file = request.getParameter("file");
        //	    String bytestart = request.getParameter("start");
        //		//获得磁盘文件条目工厂
        //		DiskFileItemFactory factory = new DiskFileItemFactory();
        //		//获取文件需要上传到的路径
        //		String path = request.getRealPath("/upload");
        //		//创建目录
        //		makeDir(path);
        //		//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
        //		//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
        //		/**
        //		 * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 
        //		 * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .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() ;
        //					
        //					request.setAttribute(name, value);
        //				}
        //				//对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
        //				else
        //				{
        //					/**
        //					 * 以下三步,主要获取 上传文件的名字
        //					 */
        //					//获取路径名
        //					String value = item.getName() ;
        //					//索引到最后一个反斜杠
        //					int start = value.lastIndexOf("\\");
        //					//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
        //					String filename = value.substring(start+1);
        //					
        //					request.setAttribute(name, filename);
        //					
        //					//真正写到磁盘上
        //					//它抛出的异常 用exception 捕捉
        //					item.write( new File(path,filename) );//第三方提供的
        //					System.out.println("获取上传文件的总共的容量:"+item.getSize());
        //					
        //手动写的
        //					OutputStream out = new FileOutputStream(new File(path,filename));
        //					
        //					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 (Exception e)
        {
            e.printStackTrace();
        }
        
        json.put("succ", true);
        
        System.out.println("post返回json数据:" + json);
        
        response.setContentType("text/plain");
        response.getWriter().write(json.toString());
    }
    
    /** 创建文件
     * <功能详细描述>
     * @param string
     * @param string2 [参数说明]
     * @return 
     * 
     * @return void [返回类型说明]
     * @throws IOException 
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private static boolean createFile(String path, String fileName)
            throws IOException
    {
        boolean creator = true;
        File myPath = new File(path, fileName);
        if (!myPath.exists())
        {
            creator = myPath.createNewFile();
        }
        return creator;
        
    }
    
    /**
     * 创建目录
     * <功能详细描述>
     * @param path
     * @return [参数说明]
     * 
     * @return boolean [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private boolean makeDir(String path)
    {
        boolean mk = true;
        File myPath = new File(path);
        if (!myPath.exists())
        {
            
            mk = myPath.mkdirs();
            
        }
        return mk;
    }
    
}
2 前端使用现成的HTML 5 API 分段发送数据

<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="description" content="Ajax文件上传断点续传">
<meta name="description" content="Ajax文件上传断点续传">
<meta name="keywords" content="web前端, css, jQuery, javascript">
<meta name="author" content="gjl">
<title>Ajax文件上传断点续传</title>
<link rel="stylesheet" href="res/demo.css" type="text/css">
<link rel="stylesheet" href="res/btn.css" type="text/css">
<link rel="stylesheet" href="res/hl.css" type="text/css">
<style>
ul { padding: 0; margin: 0; list-style-type: none; }
.upload { width: 600px; margin: 0 auto; }
.form { padding: 12px 0 30px; }
.file { position: absolute; width: 230px; height: 34px; cursor: pointer; opacity: 0; }
.file:hover + .btn-info { background-color: #39b3d7; border-color: #269abc; }
[type="submit"] { width: 100px; margin-left: 260px; float: right; visibility: hidden; }
.upload_ul { display: none; width: 100%; border: 1px solid #bbb; background-color: #fff; font-size: 12px; }
.upload_ul > li { display: table-row; opacity: 1; overflow: hidden; -webkit-transition: opacity .2s; transition: opacity .2s;
	background-image:-webkit-linear-gradient(top, #ABD9FF, #88C9FF);
	background-image:        linear-gradient(to bottom, #ABD9FF, #88C9FF);
	-moz-background-size: 0% 100%;
	background-size: 0% 100%;
	background-repeat: no-repeat;
}
.upload_title { color: #666; background-color: #f0f0f0; }
.upload_cell { display: table-cell; padding: 5px 10px; border-top: 1px solid #ddd; vertical-align:middle; }
.upload_cell:first-child { width: 50%; }
.waiting{ color: #999; }
.uploading { color: #069; }
.canceling { color: #CE4625; }
.success { color: green; }
.error { color: #f30; }
.remind { padding: 5px 10px; background-color: #eee; margin-top: 40px; color: #666; font-size: 12px;}

/*icon copyright by weiyun */
.icon { display: inline-block; width: 30px; height: 30px; background: url(res/file-small.png) no-repeat -74px -490px; vertical-align: middle; }
.icon-doc,.icon-docx{background-position:0 0}
.icon-ppt,.icon-pptx{background-position:-37px 0}
.icon-xls,.icon-xlsx{background-position:-74px 0}
.icon-pdf,.ico-pdf{background-position:-111px 0}
.icon-txt,.ico-txt{background-position:-148px 0}
.icon-msg,.ico-msg{background-position:0 -35px}
.icon-rp,.ico-rp{background-position:-37px -35px}
.icon-vsd,.ico-vsd{background-position:-74px -35px}
.icon-ai,.ico-ai{background-position:-111px -35px}
.icon-eps,.ico-eps{background-position:-148px -35px}
.icon-log,.ico-log{background-position:0 -70px}
.icon-xmin,.ico-xmin{background-position:-37px -70px}
.icon-cab,.ico-cab{background-position:-74px -70px}
.icon-psd,.ico-psd{background-position:0 -105px}
.icon-jpg,.ico-jpg{background-position:-37px -105px}
.icon-jpeg,.ico-jpeg{background-position:-37px -105px}
.icon-png,.ico-png{background-position:-74px -105px}
.icon-gif,.ico-gif{background-position:-111px -105px}
.icon-bmp,.ico-bmp{background-position:-148px -105px}
.icon-rmvb,.ico-rmvb{background-position:0 -140px}
.icon-rm,.ico-rm{background-position:0 -140px}
.icon-mod,.ico-mod{background-position:-37px -140px}
.icon-mov,.ico-mov{background-position:-74px -140px}
.icon-3gp,.ico-3gp{background-position:-111px -140px}
.icon-avi,.ico-avi{background-position:-148px -140px}
.icon-swf,.ico-swf{background-position:0 -175px}
.icon-flv,.ico-flv{background-position:-37px -175px}
.icon-mpe,.ico-mpe{background-position:-74px -175px}
.icon-asf,.ico-asf{background-position:-111px -175px}
.icon-wmv,.ico-wmv{background-position:-148px -175px}
.icon-mp4,.ico-mp4{background-position:-185px -175px}
.icon-wma,.ico-wma{background-position:0 -210px}
.icon-mp3,.ico-mp3{background-position:-37px -210px}
.icon-wav,.ico-wav{background-position:-74px -210px}
.icon-apk,.ico-apk{background-position:0 -245px}
.icon-ipa,.ico-ipa{background-position:-37px -245px}
.icon-exe,.ico-exe{background-position:-74px -245px}
.icon-msi,.ico-msi{background-position:-111px -245px}
.icon-bat,.ico-bat{background-position:-148px -245px}
.icon-fla,.ico-fla{background-position:0 -280px}
.icon-htm,.ico-htm,.icon-html,.ico-html{background-position:-37px -280px}
.icon-c,.ico-c{background-position:-111px -280px}
.icon-xml,.ico-xml{background-position:-148px -280px}
.icon-asp,.ico-asp{background-position:-185px -280px}
.icon-chm,.ico-chm{background-position:0 -315px}
.icon-hlp,.ico-hlp{background-position:-37px -315px}
.icon-ttf,.ico-ttf{background-position:-111px -315px}
.icon-otf,.ico-otf{background-position:-148px -315px}
.icon-rar,.ico-rar{background-position:0 -350px}
.icon-zip,.ico-zip{background-position:-37px -350px}
.icon-tar,.ico-tar{background-position:-74px -350px}
.icon-cab,.ico-cab{background-position:-111px -350px}
.icon-uue,.ico-uue{background-position:-148px -350px}
.icon-jar,.ico-jar{background-position:0 -385px}
.icon-7z,.ico-7z{background-position:-37px -385px}
.icon-iso,.ico-dmg{background-position:-74px -385px}
.icon-dmg,.ico-dmg{background-position:-111px -385px}
.icon-ace,.ico-ace{background-position:-148px -385px}
.icon-bak,.ico-bak{background-position:0 -420px}
.icon-tmp,.ico-tmp{background-position:-37px -420px}
.icon-old,.ico-old{background-position:-74px -420px}
.icon-document,.ico-document{background-position:0 -455px}
.icon-exec,.ico-exec{background-position:-37px -455px}
.icon-code,.ico-code{background-position:-74px -455px}
.icon-image,.ico-image{background-position:-111px -455px}
.icon-video,.ico-video{background-position:-148px -455px}
.icon-audio,.ico-audio{background-position:0 -490px}
.icon-compress,.ico-compress{background-position:-37px -490px}
.icon-unknow,.ico-unknow{background-position:-74px -490px}
.icon-filebroken,.ico-filebroken{background-position:-111px -490px}
.icon-link,.ico-link{background-position:-111px -418px}

</style>
</head>

<body>
<div id="header">
</div>
<div id="main">
	<h1>Ajax文件上传断点续传页面</h1>
    <div id="body" class="light">
    	<div id="content" class="show">
        	<h3>Ajax断点续传展示</h3>
            <div class="article_new"></div>
            <div class="demo">
            	<div class="upload">
                    <form id="form" class="form" action="/ipcc/AjaxFilesUploadServlet" enctype="multipart/form-data" >
                        <input id="file" class="file" name="file[]" multiple="" type="file"><span class="btn btn-info">请选择要上传的文件(小于1G)</span>
                        <input id="submit" class="btn btn-primary" value="上传" type="submit">
                    </form>
                    <ul id="uploadUl" class="upload_ul">
                        <li class="upload_title">
                            <div class="upload_cell">标题</div>
                            <div class="upload_cell">类型</div>
                            <div class="upload_cell">大小</div>
                            <div class="upload_cell">状态</div>
                            <div class="upload_cell">操作</div>
                        </li>
                    </ul>
                    <p class="remind">1. 点击默认展示的按钮选择文件;<br>2. 点击后出现的上传按钮进行上传</p>
                </div>
            </div>
        </div>       
    </div>
</div>
<script id="fileTemplate" type="text/template">
<li id="filelist_$id$">
	<div class="upload_cell">$name$</div>
	<div class="upload_cell"><i class="icon icon-$type$"></i></div>
	<div class="upload_cell">$size$</div>
	<div id="filestatus_$id$" class="upload_cell">$status$</div>
	<div id="fileoperate_$id$" class="upload_cell">$operate$</div>
</li>
</script>
<script>
var $ = function(id) {
	return document.getElementById(id);
};

// 一些元素
var eleForm = $("form"), eleFile = $("file"), eleSubmit = $("submit"),
	// 文件等待上传列表的容器
	eleUploadUl = $("uploadUl"),
	// 模板元素
	eleTemplate = $("fileTemplate");

// 上传文件队列数组
var fileArray = [], 
// 文件分割上传的间隙大小 10M 
fileSplitSize = 1024 * 1024 * 10 ,
// 模板HTML
htmlTemplate = eleTemplate && eleTemplate.innerHTML || '';
if (typeof history.pushState == "function") {	
	// 一些元素的状态
	var objStateElement = (function() {		
		var _$ = function(name, fileid) {
			return $("file"+ name +"_" + fileid) || { innerHTML: "" };
		};						
		
		return {
			// 上传进度条背景的控制
			backgroundSize: function(params, percent) {
				var dom = typeof params == "string"? $("filelist_" + params): params;
				if (dom) {
					dom.style.mozBackgroudSize = percent + "% 100%";
					dom.style.backgroundSize = percent + "% 100%";
				}
			},			
			wait: function(fileid) {
				// 一些状态的改变
				_$("status", fileid).innerHTML = '<span class="uploading">上传中...</span>';
				_$("operate", fileid).innerHTML = '<a href="javascript:" data-type="pause" data-id="'+ fileid +'">暂停</a>';	
			},
			keep: function(fileid) {
				_$("status", fileid).innerHTML = '<span class="waiting">等待续传...</span>';
			},
			success: function(fileid, time) {
				var eleList = $("filelist_" + fileid), 
					eleOperate = $("fileoperate_" + fileid), 
					eleStatus = $("filestatus_" + fileid);
					
				// 进度条隐藏
				this.backgroundSize(eleList, "0");
				
				// 因为元素不会删除,因此,有必要清除id
				eleStatus.id = "";
				eleOperate.id = "";
				eleList.id = "";
				// 删除本地存储的起点,完全上传成功,因此没有续传的必要
				localStorage.removeItem(fileid);
				// 状态信息再变化
				eleStatus.innerHTML = '<span class="success">'+ ((performance.now() - time > 1000)? "上": "秒") +'传成功!</span>';
				eleOperate.innerHTML = '';
				
				console.log([performance.now(), time].join());
			},
			error: function(fileid) {
				// 状态信息再变化
				_$("status", fileid).innerHTML = '<span class="error">出现异常!</span>';
				_$("operate", fileid).innerHTML = '<a href="javascript:" data-type="try" data-id="'+ fileid +'">重试</a>';	
			}	
		}							
	})();
	
	// 单文件上传
	var funFileUpload = function(fileid, onsuccess, onerror, onpause) {
		var file = fileArray[fileid], now = performance.now();
		if (!fileid || !file) return;
		onsuccess = onsuccess || function() {
			funFileUpload(fileArray[0]);	
		};
		onerror = onerror || function() {
			funFileUpload(fileArray[fileArray.indexOf(fileid) + 1]);	
		};
		onpause = onpause || function() {
			funFileUpload(fileArray[fileArray.indexOf(fileid) + 1]);	
		};
		if (file.flagPause == true) {
			onpause.call(fileid);
			return;
		}
		
		objStateElement.wait(fileid);
		
		// 文件分割上传
		// 文件大小和分割起点
		// 注释的是本地存储实现
		var size = file.size, /*start = localStorage[fileid] * 1 || 0*/ start = $("filelist_" + fileid).filesize;
		if (size == start) {
			// 已经传过了
			fileArray.shift();
			if (delete fileArray[fileid]) console.log(fileArray.join() + "---上传成功");
			objStateElement.success(fileid, now);
			// 回调
			onsuccess.call(fileid, {});
			return;
		}
		
		
		var funFileSize = function() {
			if (file.flagPause == true) {
				onpause.call(fileid);
				return;
			}
			var data = new FormData();
			data.append("name", encodeURIComponent(file.name));
			data.append("fileid", fileid);
			data.append("file", file.slice(start, start + fileSplitSize));
			data.append("start", start + "");
			var p = "?name="+encodeURIComponent(file.name)+"&fileid"+fileid+"&start"+start;
			// XMLHttpRequest 2.0 请求
			var xhr = new XMLHttpRequest();
			xhr.open("post", eleForm.action, true);				
			//xhr.setRequestHeader("X_Requested_With", location.href.split("/")[5].replace(/[^a-z]+/g,"$"));
           // xhr.setRequestHeader("Content-type", "multipart/form-data");
			// 上传进度中
			xhr.upload.addEventListener("progress", function(e) {
				objStateElement.backgroundSize(fileid, (e.loaded + start) / size * 100);
			}, false);
			// ajax成功后
			xhr.onreadystatechange = function(e) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						try {
							var json = JSON.parse(xhr.responseText);
						} catch (e) {
							objStateElement.error(fileid);
							return;
						} 
						//var json = JSON.parse(xhr.responseText);
						if (!json || !json.succ) {
							objStateElement.error(fileid);
							onerror.call(fileid, json);
							return;
						}
						
						if (start + fileSplitSize >= size) {
							// 超出,说明全部分割上传完毕
							// 上传队列中清除者一项
							fileArray.shift();
							if (delete fileArray[fileid]) console.log(fileArray.join() + "---上传成功");
							objStateElement.success(fileid, now);
							// 回调
							onsuccess.call(fileid, json);
						} else {
							// 尚未完全上传完毕						
							// 存储上传成功的文件点,以便出现意外的时候,下次可以断点续传
							localStorage.setItem(fileid, start + "");
							// 改变下一部分文件的起点位置
							start += fileSplitSize;
							console.log(start);
							// 上传下一个分割文件
							funFileSize();
						}		
					} else {
						objStateElement.error(fileid);
					}
				}
			};
			
			xhr.send(data);
		};
		
		// 文件分割上传开始
		funFileSize();
	};

	// IE10+, Chrome, FireFox等~
	eleForm.addEventListener("submit", function(event) {
		funFileUpload(fileArray[0]);		
		event.preventDefault();
	});
	
	// 选择文件后
	eleFile.addEventListener("change", function(event) {
		// 获取文件
		var files = event.target.files;
		// 遍历文件,显示文件列表信息
		var htmlFile = '', index = 0, length = files.length;
		for (; index < length; index++) {
			var file = files[index];    // Blob对象相关知识可参考:http://www.zhangxinxu.com/wordpress/?p=3725
			// console.log(file.type);
			var name = file.name, size = file.size, type = file.type || "", id = (file.lastModifiedDate + "").replace(/\W/g, '') + size + type.replace(/\W/g, '');
			var objHtml = {
				id: id,
				type: 'cloud',
				name: name,
				size: size + "B",
				status: '<span class="waiting">等待上传</span>',
				operate: '<a href="javascript:" data-type="delete" data-id="'+ id +'">删除</a>'
			}
			// name 50字符限制
			if (name.length > 50) {
				objHtml.name = '<span title="'+ name +'">'+ name.slice(0,20) + '...' + name.slice(-20) +'</span>';
			}
			
			// 文件类型与对应的图标
			var format = name.split(".");
			objHtml.type = format[format.length - 1] || "unknown";
			
			// 如果大小大于1M使用'M'为单位表示, 1位小数点
			if (size > 1024 * 1024) {
				objHtml.size = Math.round(size / (1024 * 1024) * 10) / 10 + "M";
			} else if (size > 1024) {
				// 如果大小大于1KB使用'KB'为单位表示, 1位小数点
				objHtml.size = Math.round(size / 1024 * 10) / 10 + "KB";
			}
			
			if (size > 1024 * 1024 * 1024) {
				// 如果文件大于1G, 状态为'大小溢出'
				objHtml.id = Math.random();
				objHtml.status = '<span class="error">文件过大</span>';
				objHtml.operate = '';
			} else if (fileArray.indexOf(id) != -1) {
				// 如果文件已经在列表中
				objHtml.id = Math.random();
				objHtml.status = '<span class="error">文件已存在</span>';
				objHtml.operate = '';
			} else {
				// 加入文件队列,并缓存对应的文件二进制对象
				fileArray.push(id);
				fileArray[id] = file;
			}
			
			htmlFile += htmlTemplate.replace(/\$\w+\$/gi, function(matchs) {
				var returns = objHtml[matchs.replace(/\$/g, "")];		
				return (returns + "") == "undefined"? "": returns;
			});			
		}
		// 载入HTML
		if (htmlFile !== '') {
			eleSubmit.style.visibility = "visible";
			eleUploadUl.style.display = "table";
			eleUploadUl.insertAdjacentHTML("beforeEnd", htmlFile);
			
			// 初始化进度条
			
			// 下面注释的是本地存储方法
			/*fileArray.forEach(function(fileid) {
				var loaded = localStorage[fileid] * 1;
				if (loaded > 0) {
					objStateElement.backgroundSize(fileid, loaded / fileArray[fileid].size * 100);
				}
			});*/
			
			// 现在直接使用Ajax请求
			var nameArray = fileArray.map(function(fileid) {
                //var nameSplit = fileArray[fileid].name.split("."),
				//name = nameSplit[nameSplit.length - 1];  原来是用了扩展名
				var name = nameSplit = fileArray[fileid].name
				
				return fileid + "!" + name;
			});
			var xhr_filesize = new XMLHttpRequest();
			xhr_filesize.open("GET", "/ipcc/AjaxFilesUploadServlet?filename=" + nameArray.join(), true);
			xhr_filesize.onreadystatechange = function(e) {
				if (xhr_filesize.readyState == 4) {
					if (xhr_filesize.status == 200 && xhr_filesize.responseText) {
						var json = JSON.parse(xhr_filesize.responseText);
						if (json.succ && json.data) {
							for (var key in json.data) {
								if (json.data[key] > 0 && json.data[key] < fileArray[key].size) {									
									objStateElement.backgroundSize(key, json.data[key] / fileArray[key].size * 100);
									objStateElement.keep(key);
								} 
								$("filelist_" + key).filesize = json.data[key];
							}
						}
					}
				}
			};
			xhr_filesize.send();
		}
		
		eleForm.reset();
	});
	// 文件删除等委托事件
	eleUploadUl.addEventListener("click", function(event) {
		var target = event.target, id = target && target.getAttribute("data-id");
		if (id && /^a$/i.test(target.tagName)) {
			switch (target.getAttribute("data-type")) {
				case "delete": {
					var filelist = $("filelist_" + id);
					if (filelist) {
						filelist.style.opacity = 0;
						
						// 源数据清除
						fileArray.splice(fileArray.indexOf(id), 1);
						if (delete fileArray[id]) console.log(fileArray.join() + "---删除成功");
						
						setTimeout(function() { 
							filelist.parentNode.removeChild(filelist); 
							if (fileArray.length == 0) {
								eleSubmit.style.visibility = "hidden";
								eleUploadUl.style.display = "none";
							}
						}, 220);						
					}
					break;
				}
				case "pause": {
					var eleStatus = $("filestatus_" + id);
					if (fileArray[id]) {
						fileArray[id].flagPause = true;	
						target.setAttribute("data-type", "reupload");
						target.innerHTML = "继续";
						if (eleStatus) eleStatus.innerHTML = "上传暂停";
					}
					break;
				}
				case "try": case "reupload": {
					funFileUpload(id, function() {}, function() {}, function() {});
				}
			}
		}
	});
	
} else {
	eleUploadUl.style.display = "block";
	eleUploadUl.innerHTML = '<li class="error"><p style="margin:.5em 1em;">当前浏览器不支持!试试IE10+, Chrome等~</p></li>';
}
</script>
</body></html>
 3、 使用到的 css 

1 btn.css

.btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: normal;
  line-height: 1.428571429;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
       -o-user-select: none;
          user-select: none;
}

.btn:focus {
  outline: thin dotted #333;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}

.btn:hover,
.btn:focus {
  color: #333333;
  text-decoration: none;
}

.btn:active,
.btn.active {
  background-image: none;
  outline: 0;
  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}

.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
  pointer-events: none;
  cursor: not-allowed;
  opacity: 0.65;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
          box-shadow: none;
}

.btn-default {
  color: #333333;
  background-color: #ffffff;
  border-color: #cccccc;
}

.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
  color: #333333;
  background-color: #ebebeb;
  border-color: #adadad;
}

.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
  background-image: none;
}

.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
  background-color: #ffffff;
  border-color: #cccccc;
}

.btn-primary {
  color: #ffffff;
  background-color: #428bca;
  border-color: #357ebd;
}

.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  color: #ffffff;
  background-color: #3276b1;
  border-color: #285e8e;
}

.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  background-image: none;
}

.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #428bca;
  border-color: #357ebd;
}

.btn-warning {
  color: #ffffff;
  background-color: #f0ad4e;
  border-color: #eea236;
}

.btn-warning:hover,
.btn-warning:focus,
.btn-warning:active,
.btn-warning.active,
.open .dropdown-toggle.btn-warning {
  color: #ffffff;
  background-color: #ed9c28;
  border-color: #d58512;
}

.btn-warning:active,
.btn-warning.active,
.open .dropdown-toggle.btn-warning {
  background-image: none;
}

.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
  background-color: #f0ad4e;
  border-color: #eea236;
}

.btn-danger {
  color: #ffffff;
  background-color: #d9534f;
  border-color: #d43f3a;
}

.btn-danger:hover,
.btn-danger:focus,
.btn-danger:active,
.btn-danger.active,
.open .dropdown-toggle.btn-danger {
  color: #ffffff;
  background-color: #d2322d;
  border-color: #ac2925;
}

.btn-danger:active,
.btn-danger.active,
.open .dropdown-toggle.btn-danger {
  background-image: none;
}

.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
  background-color: #d9534f;
  border-color: #d43f3a;
}

.btn-success {
  color: #ffffff;
  background-color: #5cb85c;
  border-color: #4cae4c;
}

.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
  color: #ffffff;
  background-color: #47a447;
  border-color: #398439;
}

.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
  background-image: none;
}

.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
  background-color: #5cb85c;
  border-color: #4cae4c;
}

.btn-info {
  color: #ffffff;
  background-color: #5bc0de;
  border-color: #46b8da;
}

.btn-info:hover,
.btn-info:focus,
.btn-info:active,
.btn-info.active,
.open .dropdown-toggle.btn-info {
  color: #ffffff;
  background-color: #39b3d7;
  border-color: #269abc;
}

.btn-info:active,
.btn-info.active,
.open .dropdown-toggle.btn-info {
  background-image: none;
}

.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
  background-color: #5bc0de;
  border-color: #46b8da;
}

.btn-link {
  font-weight: normal;
  color: #428bca;
  cursor: pointer;
  border-radius: 0;
}

.btn-link,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
  background-color: transparent;
  -webkit-box-shadow: none;
          box-shadow: none;
}

.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
  border-color: transparent;
}

.btn-link:hover,
.btn-link:focus {
  color: #2a6496;
  text-decoration: underline;
  background-color: transparent;
}

.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
  color: #999999;
  text-decoration: none;
}

.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}

.btn-sm,
.btn-xs {
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 3px;
}

.btn-xs {
  padding: 1px 5px;
}

.btn-block {
  display: block;
  width: 100%;
  padding-right: 0;
  padding-left: 0;
}

.btn-block + .btn-block {
  margin-top: 5px;
}

input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
  width: 100%;
}

 2.demo.css

body{background:#a0b3d6; font-size:84%; margin:0; line-height:1.5; color:#333; font-family:Arial, sans-serif;}
a{color:#34538b; text-decoration:none;}a:hover{text-decoration:underline;}
input,select,textarea{font-size:100%;}
#header{height:60px; padding:0 0 0 40px;}
#header .logo{margin-top:12px; overflow:hidden; float:left;}
#main{width:100%; background:#beceeb; overflow:hidden;}
#main h1{line-height:40px; margin:0; text-align:center; font-size:1.3em; background:#c1d5eb; font-family:'kaiti','microsoft yahei'; text-shadow:0px 1px 0px #f2f2f2;}
#body{padding:0; overflow:hidden;}
#body .part{width:50%; min-height:500px; _height:500px; background:white;}
#code{float:left; margin-left:-1px; margin-bottom:-999em; padding-bottom:999em;}
#effect{float:right; margin-right:-1px; margin-bottom:-999em; padding-bottom:999em;}
#body h3{line-height:30px; margin:0; font-size:1.1em; background:#f0f3f9; padding-left:10px; border-bottom:1px solid #ededed; color:#4e4e4e; text-shadow:0px 1px 0px white;}
#footer{line-height:1.3; padding:15px 0; border-top:1px solid #486aaa; font-family:'Lucida Grande',Verdana, Sans-Serif; text-align:center; text-shadow:1px 1px #cad5eb;}
#footer:before{display:block; height:1px; content:''; background-color:#909BAF; color:#aaa; overflow:hidden; position:relative; top:-15px;}
#footer img{margin-bottom:-3px;}
.show{padding-bottom:20px;}
.show h5{font-size:0.9em; line-height:20px; padding:0 0 2px 2px; margin:10px 8px 0; border-bottom: 1px dotted #e5e5e5;}
.show .demo{padding:10px; *zoom:1;}
.show .demo:after{display:table; content:""; clear:both;}
pre{font-family:'simsun';}
#ad, .ad {width:468px; height:60px; margin:0 auto; color: #fff; }
.ad { position: absolute; top: 0; right: 0; text-align: center; font-size: 12px; background-color: #67748A; background-color: rgba(0,0,0,.35); }
@media screen and (max-width: 468px) {
    #ad { display: none; }
}
@media screen and (max-width: 700px) {
   .ad { display: none; }
}
.light{background:#f0f3f9;}
#content{min-height:500px; _height:500px; background:white; border:solid #cad5eb; border-width:0 2px; font-family:'Lucida Grande',Verdana;}
.article{font-family:Arial; padding:10px 0; font-size:0.86em; clear:both;}
.article_new{ margin:-33px 10px 0 0; font-family:Arial; padding:10px 0; font-size:0.86em; clear:both; text-align:right;}
#back{margin-top:-25px; position:absolute; right:10px;}

  3.hl.css

/* Generics */

.DlHighlight{
  font:13px/1.3 monospace;
  padding:5px 10px;
  margin:0;
  white-space:pre-wrap;
  word-wrap:break-word;
}

.DlHighlight pre{margin:0; padding:0;}

.DlHighlight .keyword{color:#00f;}

.DlHighlight .builtin{color:#22c;}

.DlHighlight .string{color:#282;}
.DlHighlight .string .before, .DlHighlight .string .after{color:#040;}

.DlHighlight .regexp{color:#b2c;}
.DlHighlight .regexp .before, .DlHighlight .regexp .after{color:#509;}

.DlHighlight .comment{color:#c22;}
.DlHighlight .comment-line{color:#999999;}
.css .comment-line{color:#22c;}
.DlHighlight .comment .before, .DlHighlight .comment .after{color:#baa;}

.DlHighlight .hashkey{color:#a51;}

.DlHighlight .hasharrow{color:#f00;}

.DlHighlight .paren{color:#000099;}

.DlHighlight .operator{color:#077;}

.DlHighlight .error{background-color:#c00; color:#fff;}

.DlHighlight .defun{}

.DlHighlight .line-numbers {
  float:left;
  margin-left:-4.5em;
  width:3em;
  text-align:right;
  color:#999;
  font:0.9em tahoma,verdana,sans-serif;
  padding-top:0.05em;
}
.DlHighlight .line-numbers:after{content:"." }

/* XML */

.DlHighlight .xml-tag-close .before{color:#52a;}

.DlHighlight .xml-entity{color:#b2a;}
.DlHighlight .xml-entity .before, .DlHighlight .xml-entity .after{color:#607;}
.DlHighlight .xml-tag{font-weight:normal;}
/* CSS */
.DlHighlight .css-block-open,.DlHighlight .css-block-close{color:#ff00ff;}
.DlHighlight .css-class{color:#ff00ff;}
.DlHighlight .css-pseudo-class{color:#777;}
.DlHighlight .css-id{color:#ff00ff;}
.DlHighlight .css-color-spec{color:#0000ff;}
.DlHighlight .css-length{color:#0000ff;}
.DlHighlight .css-length .after{}
.DlHighlight .css-declaration-kw{color:#000099;}
.DlHighlight .css-comma{color:red;}
4 使用到的图片 


5 运行效果图 





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值