swfupload

jar

commons-fileupload-1.2.jar

commons-io-1.3.2.jar


web.xml

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<servlet>
		<servlet-name>FileUploadServlet</servlet-name>
		<servlet-class>com.huliang.fileupload.FileUploadServlet</servlet-class>
	</servlet>
	<filter>
		<filter-name>code</filter-name>
		<filter-class>filter.code</filter-class>
		<init-param>
			<param-name>cd</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>code</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/FileUploadServlet.htm</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

index.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%

	//这一段代码是用来生成处理文件
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";

	StringBuffer uploadUrl = new StringBuffer("http://");
	uploadUrl.append(request.getHeader("Host"));
	uploadUrl.append(request.getContextPath());
	uploadUrl.append("/FileUploadServlet.htm");
	System.out.println(uploadUrl);
%>
<html>
	<head>

		<style type="text/css">
<!--
body {
	margin-left: 10px;
	margin-top: 10px;
}

.table1 td {
	height: 22px;
	line-height: 22px;
}

.a1 {
	color: #000;
	font-size: 12px
}

.a1:link {
	color: #000;
	text-decoration: underline;
	cursor: hand;
	font-size: 12px
}

.a1:visited {
	color: #000;
	text-decoration: underline;
	cursor: hand;
	font-size: 12px
}

.a1:hover {
	color: #000;
	text-decoration: underline;
	cursor: hand;
	font-size: 12px
}

.a1:active {
	color: #000;
	text-decoration: underline;
	cursor: hand;
	font-size: 12px
}
-->
</style>
		<base href="<%=basePath%>">
		<link href="css/default.css" rel="stylesheet" type="text/css" />
		<link rel="stylesheet" href="css/button.css" type="text/css" />
		<script type="text/javascript" src="js/swfupload/swfupload.js"></script>
		<script type="text/javascript" src="js/swfupload/swfupload.queue.js"></script>
		<script type="text/javascript" src="js/swfupload/fileprogress.js"></script>
		<script type="text/javascript" src="js/swfupload/handlers.js"></script>
		<script type="text/javascript">
		var upload1;

		window.onload = function() {
			upload1 = new SWFUpload({
				// Backend Settings
				upload_url: "<%=uploadUrl.toString()%>",//处理上传业务逻辑的代码的路径
				post_params: {"PHPSESSID" : "brcvfb84ia3b34ot8jcs9rr8f4"},
				
				// File Upload Settings
				file_size_limit : "104857600",	// 100MB
				file_types : "*.*",
				file_types_description : "所有文件",
				file_upload_limit : "0",
				file_queue_limit : "0",

				// Event Handler Settings (all my handlers are in the Handler.js file)
				file_dialog_start_handler : fileDialogStart,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,

				// Button Settings
				button_image_url : "images/XPButtonUploadText_61x22.png",
				button_placeholder_id : "spanButtonPlaceholder1",
				button_width: 61,
				button_height: 22,
				
				// Flash Settings
				flash_url : "js/swfupload/swfupload.swf",	//flash_url的路径
				

				custom_settings : {
					progressTarget : "fsUploadProgress1",
					cancelButtonId : "btnCancel1"
				},
				
				// Debug Settings
				debug: false
			});
			function startUploadFile(){
				upload1.startUpload();
			}

	     }
	</script>

	</head>
	<body>
		<form id="form1" action="" method="post"
			enctype="multipart/form-data">
			<div>
				<div class="fieldset flash" id="fsUploadProgress1">
					<span class="legend">上传文件</span>
				</div>
				<div style="padding-left: 5px;">
					<span id="spanButtonPlaceholder1"></span>
					<input id="btnCancel1" type="button" value="Cancel Uploads"
						οnclick="cancelQueue(upload1);" disabled="disabled"
						style="margin-left: 2px; height: 22px; font-size: 8pt;" />
					<br />
				</div>
			</div>
		</form>

	</body>
</html>






js/swfupload/fileprogress.js

/*
	A simple class for displaying file information and progress

	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/
/*
 * 我感觉这个好像完全都是进度条内容,跟队列没有什么关系
 */
// Constructor
// file is a SWFUpload file object 文件是一个swfupload 文件对象
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements


//在handlers.js这个文件当中我们看到每一次都会生成一个进度条,在那里只是调用了一个函数
//这个函数的名字就是 FileProgress,就是下面的这个函数
function FileProgress(file, targetID) {
	//设置进度条的id
	this.fileProgressID = file.id;
    //设置进度条的不透明度
	this.opacity = 100;
	this.height = 0;//设置进度条的高度
	
    //获取当前进度条的element
	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	//如果这个element不是空
	if (!this.fileProgressWrapper) {
		//这个只是设置了id,别的什么功能都没有干
		this.fileProgressWrapper = document.createElement("div");//创建一个div标签
		this.fileProgressWrapper.className = "progressWrapper";//设置它的className为 progressWrapper
		this.fileProgressWrapper.id = this.fileProgressID;//设置它的id为文件的id

		this.fileProgressElement = document.createElement("div");//创建一个div标签
		this.fileProgressElement.className = "progressContainer";//设置它的className为progressContainer
		
		//创建一个标签<a >
		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";//设置className为"progressCancel"
		progressCancel.href = "#";//设置href的内容为"#"
		progressCancel.style.visibility = "hidden";//设置为不可见
		progressCancel.appendChild(document.createTextNode(" "));//穿件一个文本节点,追加到progressCancel这个标签上面
		
		//再次创建一个div标签(这个是用来显示文件的名称的)
		var progressText = document.createElement("div");
		progressText.className = "progressName";//设置这个标签的className为"progressName"
		progressText.appendChild(document.createTextNode(file.name));
        
		//创建一个div标签,设置标签的className为progressBarInProgress
		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		//穿件一个div标签,设置标签的className为progressBarSatus
		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = " ";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.reset();
	}

	this.height = this.fileProgressWrapper.offsetHeight;
	this.setTimer(null);


}

//我们发现了这里有这个setTimer,我们发现跟vc不一样
//这个函数的含义是,给这个进度条设置定时器
FileProgress.prototype.setTimer = function (timer) {
	this.fileProgressElement["FP_TIMER"] = timer;
};
//获取进度条的定时器
FileProgress.prototype.getTimer = function (timer) {
	return this.fileProgressElement["FP_TIMER"] || null;
};

//重启
FileProgress.prototype.reset = function () {
	this.fileProgressElement.className = "progressContainer";

	this.fileProgressElement.childNodes[2].innerHTML = " ";
	this.fileProgressElement.childNodes[2].className = "progressBarStatus";
	
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = "0%";
	
	this.appear();	
};

//在上传的过程中,进度条的颜色会显示为绿色,
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";

	this.appear();	//掉用appear()这个函数
};

//当上传完成的时候设置一个定时器,执行消失这个函数
//上传完成的时候,进度条惠显示为蓝色,但是如何设置呢?
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	//每
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 10000));
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 5000));
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 2000));
};

//这个类似与java类的set函数,当然我们在handlers当中也会掉用这个函数,用来设置
//进度条下面的一行小字的的信息
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

//用来设置是否能够触发取消按钮
// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

//设置进度条的出现(这个函数就完成两个动作,一个是设置不透明度为100,就是开始显示,另一个是设置好定时器)
FileProgress.prototype.appear = function () {
	//如果没有定时器,那么我们就给他设定一个定时器
	if (this.getTimer() !== null) {
		clearTimeout(this.getTimer());
		this.setTimer(null);
	}
	
	if (this.fileProgressWrapper.filters) {
		try {
			//设置滤镜的不透明度为100
			this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			//如果没有正常出事化,那么这个滤镜的不透明度会看起来是100,就好好像什么都没有作用一样
			this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
		}
	} else {
		this.fileProgressWrapper.style.opacity = 1;
	}
		
	this.fileProgressWrapper.style.height = "";
	
	this.height = this.fileProgressWrapper.offsetHeight;
	this.opacity = 100;
	this.fileProgressWrapper.style.display = "";
	
};

//这个设置的内容分连部分
//第一部分,递减不透明度赋值给滤镜,递减高度,赋值给滤镜
//第二部分,设置定时器,定制执行disapper这个函数,我不太明白,因为这个函数的定时器定时两次是什么原因?
//设置进度条的消失
// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	//不透明度每一次减少15,高度每一次减少4,也就是说,6秒以后开始消失,高度会在25秒内消失完(但是高度很小,所以看起来一次也消失了很多)
	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps
	
	//如果不透明度>0的时候
	if (this.opacity > 0) {
		//每一次递减15
		this.opacity -= reduceOpacityBy;
		//如果不透明度<0,设置不透明度为0
		if (this.opacity < 0) {
			this.opacity = 0;
		}
        //如果滤镜存在,那么设置滤镜的不透明度为当前的不透明度
		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}
	//高度同上
	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}
	
	//如果高度>0或者不透明度>0(重复执行这个函数)
	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		this.setTimer(setTimeout(function () {
			oSelf.disappear();
		}, rate));
	} else {
		this.fileProgressWrapper.style.display = "none";
		this.setTimer(null);
	}
};

js/swfupload/handlers.js

/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
 
//这里不是删除一个队列,而是删除队列中的一个元素,从下面的id当中我们可一个看到
//而且处理函数是停止一个stopUpload();
function cancelQueue(instance) {
	document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	
}

/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileDialogStart() {
	/* I don't need to do anything here */
}

//当文件放置到queue当中的时候
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		
		//生成一个进度条
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Pending...");//进度条的状态是"Pending...."(就是在进度条下面显示的文字是pending)
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

function fileQueueError(file, errorCode, message) {
	try {
		//如果超出队列显示
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}
        //生成一个进度条,通过progressTarget
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);
		//
		switch (errorCode) {
		//如果超出文件大小的限制
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		//如果上传0字节的文件
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		//如果上传非法文件
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		//如果上传队列超出限制
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("You have selected too many files.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}
//当文件上传完成的时候,删除的按钮无法使用
function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (this.getStats().files_queued > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}
//开始上传文件
function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and return true to indicate that the upload should start */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Uploading...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {
	}
	
	return true;
}

//上传文件
function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Uploading...");
	} catch (ex) {
		this.debug(ex);
	}
}

//上传文件成功的时候
function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);

	} catch (ex) {
		this.debug(ex);
	}
}
//这个函数跟上面的函数有什么区别?
//我想自动进行下一个上传动作,所以我将会调用startUpload 在这里
function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = true;
		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

//上传文件错误的时候
function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus("Configuration Error");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus("File not found.");
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

js/swfupload/swfupload.js(官方的文件,不用修改)


js/swfupload/swfupload.queue.js

/*
	Queue Plug-in
	
	Features:
 		*Adds a cancelQueue() method for cancelling the entire queue.
 		*All queued files are uploaded when startUpload() is called.
 		*If false is returned from uploadComplete then the queue upload is stopped.
		 If false is not returned (strict comparison) then the queue upload is continued.
 		*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
		 Set the event handler with the queue_complete_handler setting.
	特性:
		增加了一个 cancelQueue() 用来删除整个队列
		当startUpload()这个函数被调用的时候,所有的队列文件都会被上传
		如果uploadComplete返回一个false,那么上传队列就会停止
		QueueComplete event当所有的序列都上传完成。
		
*/

var SWFUpload;
if (typeof (SWFUpload) === "function") {
	SWFUpload.queue = {};
	//prototype应该是指的属性,这句话的意思就是给SWFUpload的initSettings属性赋值
	SWFUpload.prototype.initSettings = (function(oldInitSettings) {
		return function() {
			if (typeof (oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}

			this.queueSettings = {};

			this.queueSettings.queue_cancelled_flag = false;
			this.queueSettings.queue_upload_count = 0;

			this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
			this.settings.queue_complete_handler = this.settings.queue_complete_handler
					|| null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function(fileID) {
		this.queueSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", [ fileID ]);
	};

	SWFUpload.prototype.cancelQueue = function() {
		this.queueSettings.queue_cancelled_flag = true;
		this.stopUpload();

		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};

	SWFUpload.queue.uploadStartHandler = function(file) {
		var returnValue;
		if (typeof (this.queueSettings.user_upload_start_handler) === "function") {
			returnValue = this.queueSettings.user_upload_start_handler.call(
					this, file);
		}

		// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
		returnValue = (returnValue === false) ? false : true;

		this.queueSettings.queue_cancelled_flag = !returnValue;

		return returnValue;
	};

	SWFUpload.queue.uploadCompleteHandler = function(file) {
		var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
		var continueUpload;

		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.queueSettings.queue_upload_count++;
		}

		if (typeof (user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false
					: true;
		} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			// If the file was stopped and re-queued don't restart the upload
			continueUpload = false;
		} else {
			continueUpload = true;
		}

		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0
					&& this.queueSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.queueSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler",
						[ this.queueSettings.queue_upload_count ]);
				this.queueSettings.queue_upload_count = 0;
			} else {
				this.queueSettings.queue_cancelled_flag = false;
				this.queueSettings.queue_upload_count = 0;
			}
		}
	};
}


js/swfupload/swfupload.swf(官方的文件,不用修改)


images(文件夹下面有两个文件)

这两站都是图片


css文件下面有两个css文件

button.css

.btn3_mouseout {
	BORDER-RIGHT: #99CCCC 1px solid;
	PADDING-RIGHT: 2px;
	BORDER-TOP: #99CCCC 1px solid;
	PADDING-LEFT: 2px;
	FONT-SIZE: 12px;
	FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#C3DAF5);
	BORDER-LEFT: #99CCCC 1px solid;
	CURSOR: hand;
	COLOR: black;
	PADDING-TOP: 1px;
	BORDER-BOTTOM: #99CCCC 1px solid;
	HEIGHT: 20px
}

.btn3_mouseover {
	BORDER-RIGHT: #99CCCC 1px solid;
	PADDING-RIGHT: 2px;
	BORDER-TOP: #99CCCC 1px solid;
	PADDING-LEFT: 2px;
	FONT-SIZE: 12px;
	FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#0066CC);
	BORDER-LEFT: #99CCCC 1px solid;
	CURSOR: hand;
	COLOR: black;
	PADDING-TOP: 1px;
	BORDER-BOTTOM: #99CCCC 1px solid;
	HEIGHT: 20px
}

.btn3_mousedown {
	BORDER-RIGHT: #FFE400 1px solid;
	PADDING-RIGHT: 2px;
	BORDER-TOP: #FFE400 1px solid;
	PADDING-LEFT: 2px;
	FONT-SIZE: 12px;
	FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#0066CC);
	BORDER-LEFT: #FFE400 1px solid;
	CURSOR: hand;
	COLOR: black;
	PADDING-TOP: 1px;
	BORDER-BOTTOM: #FFE400 1px solid;
	HEIGHT: 20px
}

.btn3_mouseup {
	BORDER-RIGHT: #99CCCC 1px solid;
	PADDING-RIGHT: 2px;
	BORDER-TOP: #99CCCC 1px solid;
	PADDING-LEFT: 2px;
	FONT-SIZE: 12px;
	FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#C3DAF5);
	BORDER-LEFT: #99CCCC 1px solid;
	CURSOR: hand;
	COLOR: black;
	PADDING-TOP: 1px;
	BORDER-BOTTOM: #99CCCC 1px solid;
	HEIGHT: 20px
}

default.css

html, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
 caption, tbody, tfoot, thead, th, {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	font-family: inherit;
	vertical-align: baseline;
}
td{	
	word-break:break-all;
}
/* remember to define focus styles! */
:focus { outline: 0; }
body {
	line-height: 1;
	color: black;
	background: white;
}

table {
	border-collapse: separate;
	border-spacing: 0;
}
caption, th, td {
	font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after { 
	content: "";
}
blockquote, q {
	quotes: "" "";
}

html, 
body {
	margin: 0;
	padding: 0;
	width: 100%;
	font: 12px/1.4em Helvetica, Arial, sans-serif;
}

a { 
	color: #385ea2; 
	text-decoration: none; 
}
a:hover { text-decoration: underline; }

strong { font-weight: 700; }

h1 {
	font: 28px/1em  Arial, Helvetica, sans-serif;
	padding: 60px 20px 20px;
	margin-bottom: 15px;
	color: #333;
	text-decoration: none;
}

h1 a{
	color: #fff;
	text-decoration: none;
}

h2 { 
	font-size: 22px; 
	font-weight: 300;
	padding-top: 1em;
	padding-bottom: .25em;
}


p { 
	margin-top: .25em;
	margin-bottom: .5em;
}

ul { padding: 4px 5px; }
ul li { 
	padding: 4px 5px; 
	margin: 0 20px;
	list-style:square; 
}

code {
	display: block;
	background:#edffb8 none repeat scroll 0%;
	border-color:#b2da3a;
	border-style:solid;
	border-width:1px 0;
	font-size: 1em;
	margin: 1em 0pt;
	overflow:auto;
	padding: 0.3em 0.4em;
	white-space:pre;
}

/* -- Layout ------------------------------- */

#content { margin: 20px 90px; }

div.fieldset {
	border:  1px solid #afe14c;
	margin: 10px 0;
	padding: 20px 10px;
}
div.fieldset span.legend {
	position: relative;
	background-color: #FFF;
	padding: 3px;
	top: -30px;
	font: 700 14px Arial, Helvetica, sans-serif;
	color: #73b304;
}

div.flash {
	width: 375px;
	margin: 10px 5px;
	border-color: #D9E4FF;

	-moz-border-radius-topleft : 5px;
	-webkit-border-top-left-radius : 5px;
    -moz-border-radius-topright : 5px;
    -webkit-border-top-right-radius : 5px;
    -moz-border-radius-bottomleft : 5px;
    -webkit-border-bottom-left-radius : 5px;
    -moz-border-radius-bottomright : 5px;
    -webkit-border-bottom-right-radius : 5px;
}

select,
textarea { 
	border-width: 1px; 
	margin-bottom: 10px;
	padding: 2px 3px;
}

input[disabled]{ border: 1px solid #ccc } /* FF 2 Fix */

/* -- Table Styles ------------------------------- */
td {
	font: 10pt Helvetica, Arial, sans-serif;
	vertical-align: top;
}

.progressWrapper {
	width: 357px;
	overflow: hidden;
}

.progressContainer {
	margin: 5px;
	padding: 4px;
	border: solid 1px #E8E8E8;
	background-color: #F7F7F7;
	overflow: hidden;
}

.message {
	margin: 1em 0;
	padding: 10px 20px;
	border: solid 1px #FFDD99;
	background-color: #FFFFCC;
	overflow: hidden;
}

.red {
	border: solid 1px #B50000;
	background-color: #FFEBEB;
}

.green {
	border: solid 1px #DDF0DD;
	background-color: #EBFFEB;
}

.blue {
	border: solid 1px #CEE2F2;
	background-color: #F0F5FF;
}

.progressBarInProgress,
.progressBarComplete,
.progressBarError {
	font-size: 0;
	width: 0%;
	height: 2px;
	background-color: blue;
	margin-top: 2px;
}

.progressBarComplete {
	width: 100%;
	background-color: green;
	visibility: hidden;
}

.progressBarError {
	width: 100%;
	background-color: red;
	visibility: hidden;
}

.progressBarStatus {
	margin-top: 2px;
	width: 337px;
	font-size: 7pt;
	font-family: Arial;
	text-align: left;
	white-space: nowrap;
}

a.progressCancel {
	font-size: 0;
	display: block;
	height: 14px;
	width: 14px;
	background-image: url(../images/cancelbutton.gif);
	background-repeat: no-repeat;
	background-position: -14px 0px;
	float: right;
}

a.progressCancel:hover {
	background-position: 0px 0px;
}

.swfupload {
	vertical-align: top;
}

java文件

filter/code.java

package filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class code implements Filter {
	String geshi;
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		
		arg0.setCharacterEncoding(geshi);
		arg1.setCharacterEncoding(geshi);
		arg2.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

		 geshi = arg0.getInitParameter("cd");
	}

}

com.huliang.fileupload

package com.huliang.fileupload;

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

/*
 *  这个是一个过滤器
 */
public class FileUploadServlet extends HttpServlet {
	private static String base = "D:\\a";
	private static ServletFileUpload upload;
	static {
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 设置内存缓冲区,超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置

		File file = new File(base);// 在临时文件存贮位置生成一个文件
		if (!file.exists())// 如果这个文件不存在,那么就生成一个路径
			file.mkdirs();
		factory.setRepository(file);

		upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);
		upload.setHeaderEncoding("UTF-8");
	}

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");// 设置编码方式为utf-8

		try {
			// 生成一个list对象
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			String fileName = null;
			for (int i = 0; i < items.size(); i++) {
				item = (FileItem) items.get(i);
				fileName = base + File.separator + item.getName();

				// 保存文件
				if (!item.isFormField() && item.getName().length() > 0) {
					// 获取文件的后缀
					String filename = item.getName();
					String extension = filename.substring(filename
							.lastIndexOf("."), filename.length());

					// 应该是写文件
					item.write(new File(fileName));
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值