uploadify批量上传文件

原创 2012年03月26日 23:33:28

搜索了一些关于批量上传性能的问题,今天看到了uploadify

觉得特别的不错,用jquery实现了批量的上传功能,不仅强大,同时也实现了进度条的功能

稍稍做一点美化就非常棒的一个操作,下面就简单的总结一下使用这个扩展应用的步骤

http://www.uploadify.com/

去官网上面下载query.uploadify.v2.1.4.js目前我用的最新的是这个版本,不过里面的demo是php的

不过对于js框架的时候,既然php能用java也同样可以,对着例子看了一些网上的例子,做了一个笔记详细写了一下部署过程:

创建了一个web project

commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar

首先把这两个jar文件引入了path

然后创建了一个servlet

Upload.java(用的MyEclipse自动配置了web.xml部署描述符)

//Upload.java
package com.uploadify.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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;

import com.uploadify.utils.IPTimeStamp;

public class Upload extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String savePath = this.getServletConfig().getServletContext()
				.getRealPath("");
		// 得到项目的工作目录
		savePath = savePath + "/uploads/";
		File f1 = new File(savePath);
		// 如果没有的话就创建目录
		if (!f1.exists()) {
			f1.mkdirs();
		}
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String extName = "";
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {

				// 解析文件
				name = item.getName();
				long size = item.getSize();
				String type = item.getContentType();
				if (name == null || name.trim().equals("")) {
					continue;
				}
				// 得到文件的扩展名
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				File file = null;
				do {
					// 利用客户端IP+时间+三位随机数字生成非重复文件名:
					name = new IPTimeStamp().getIPTimeStampRandom();
					file = new File(savePath + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);
				try {
					item.write(saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		response.getWriter().print(name + extName);
	}

}
生成文件名字的Utils类,可以清楚的记录名字,然后对上传的文件进行处理,并且防止文件名字重复

//PTimeStamp.java
package com.uploadify.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class IPTimeStamp {
	private String ip;
	private Date date;
	private SimpleDateFormat format;

	public IPTimeStamp() {
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getTimeStamp() {
		format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return format.format(new Date());
	}

	public String addZero(String str, int len) {
		StringBuffer sb = new StringBuffer();
		sb.append(str);
		while (sb.length() < len) {
			sb.insert(0, "0");
		}
		return sb.toString();
	}

	public String getIPTimeStampRandom() {
		StringBuffer sb = new StringBuffer();
		String[] ips = this.ip.split("\\.");

		for (int j = 0; j < ips.length; j++) {
			// System.out.println(ips[j]);
			sb.append(this.addZero(ips[j], 3));
		}
		sb.append(this.getTimeStamp());
		Random rod = new Random();
		for (int i = 0; i < 3; i++) {
			sb.append(rod.nextInt(10));
		}
		return sb.toString();
	}
}


部署描述符

<!--web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>Upload</servlet-name>
    <servlet-class>com.uploadify.servlet.Upload</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Upload</servlet-name>
    <url-pattern>/Upload</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


在WebROOT下面创建folder->js

放入解压包里面的

jquery.uploadify.v2.1.4.js
jquery.uploadify.v2.1.4.min.js
jquery-1.4.2.min.js
swfobject.js

css->

uploadify.css

images->

cancel.png
<!--index.jsp-->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>My JSP 'index.jsp' starting page</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
		<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/swfobject.js"></script>
		<script type="text/javascript" src="js/jquery.uploadify.v2.1.4.js"></script>
		<script type="text/javascript">
        $(document).ready(function() {
            $("#uploadify").uploadify({
                'uploader'       : 'uploadify.swf',
                'script'         : 'Upload',
                'cancelImg'      : 'images/cancel.png',
                'folder'         : 'uploads',
                'queueID'        : 'fileQueue',
                'auto'           : false,
                'multi'          : true,
                'simUploadLimit' : 2,
                'buttonText'     : 'BROWSE'
            });
        });
        </script>
	</head>

	<body>
		<div id="fileQueue"></div>
		<input type="file" name="uploadify" id="uploadify" />
		<p>
			<a href="javascript:jQuery('#uploadify').uploadifyUpload()">开始上传</a> 
			<a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a>
		</p>
	</body>
</html>

验证成功,相当漂亮

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Uploadify自定义提示信息

版本:Uploadify Version 3.2 官网:http://www.uploadify.com Uploadify是一款基于Jquery的上传插件,用起来很方便。但上传过程中的提示语...

Uploadify多文件上传

http://blog.csdn.net/han_yankun2009/article/details/17100405 由于考试系统的需求,需要将听力文件或是图片上传到服务器中的数据库中,而文...

【Mongo】uploadify插件帮助实现批量上传

【项目需求】     在整个考试系统中,我们可将其分为三个部分:考试前、考试中以及考试后。最近一周都在做考试前的配置,我负责的是题库模块,学生考试时是需要从题库中抽题的。而题库,又有不同的题型,单选题...

struts2整合uploadify插件实现批量上传,上传成功后跳转并传递参数

<script type="text/javascript" src="stati
  • yhhazr
  • yhhazr
  • 2012-03-03 16:57
  • 5476

uploadify批量上传 代码示范

如何使用     1.下载uploadify(http://www.uploadify.com/) 2.创建一个web项目 3.  添加项目所需的jar包commons-fileupload-1.2....

uploadify+批量上传文件+java

<% String path = request.getContextPath(); Strin

【uploadify3.1使用二】批量文件、图片上传

1、uploadify3.1的使用方式有别与2.x的版本,3.1版本已经把swfobject.js 给嵌入jquery.uploadify-3.1.min.js中, 2、引入资源文件 ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)