swfupload文件上传组件 服务端用servlet配置教程

5 篇文章 0 订阅
5 篇文章 0 订阅

swfupload是个不错的上传组件,可以实现无刷新上传图片,并返回自己想要的数据,今天写了一个用java servlet来作为服务端接收客户端文件,自己在项目中也有使用,功能是实现远程上传文件并返回上传后在服务端的文件路径。

1,在官网下载swfupload,地址:http://demo.swfupload.org

2,编写上传页面(这里的上传页面完全是从官网整过来的),并在下载的文件中找到以下html代码中的js文件并并入,(我下载的包中没有default.css文件,以下css也是我是官网copy过来的,里面用到一个按钮的样式,包括图片,如果不想自己写也可以先整过来),部分详情看页面注释的几个函数。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>上传图片</title>
<jsp:include page="/home/head_html.jsp" flush="true" />
<script type="text/javascript" src="/myimg/copy.js"></script>
<link href="upload/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="upload/swfupload.js"></script>
<script type="text/javascript" src="upload/swfupload.swfobject.js"></script>
<script type="text/javascript" src="upload/fileprogress.js"></script>
<script type="text/javascript" src="upload/handers.js"></script>
<script type="text/javascript">
		var swfu;

		window.onload = function () {
			swfu = new SWFUpload({
				// Backend settings  
				upload_url: "<%=basePath%>/upload/uploadImg",//服务端接收的servlet地址
				file_post_name: "resume_file",

				// Flash file settings
				file_size_limit : "10 MB",
				file_types : "*.*",			// or you could use something like: "*.doc;*.wpd;*.pdf",
				file_types_description : "All Files",
				file_upload_limit : "0",
                              // 向服务端传递的参数 user代表上传的用户,p我是用来代表某个产品类别的意思,作为上传文件的路径用,具体的看自己需求
                         post_params: {
	                "user" : "admin",
	                "p" : "x"
	            },
				file_queue_limit : "1",
				use_query_string : true,
				// Event handler settings
				swfupload_loaded_handler : swfUploadLoaded,
				
				file_dialog_start_handler: fileDialogStart,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,//当你选择文件后执行的函数,你可以在这个函数里设置成选择文件后直接上传或者提交表单时再上传
				
				//upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,//文件上传成功后执行的函数,服务端返回的数据也是从这里获取,详情在handlers.js中
				upload_complete_handler : uploadComplete,//文件上传完成后的操作

				// Button Settings
				button_image_url : "images/XPButtonUploadText_61x22.png",
				button_placeholder_id : "spanButtonPlaceholder",
				button_width: 61,
				button_height: 22,
				
				// Flash Settings
				flash_url : "upload/Flash/swfupload.swf",

				custom_settings : {
					progress_target : "fsUploadProgress",
					//upload_successful : false
				},
				
				// Debug settings
				debug: false
			});

		};
	</script>
</head>
<body>
<div id="header">
	<h1 id="logo"><a href="../">SWFUpload</a></h1>
	<div id="version">v2.2.0</div>
</div>

<div id="content">

	<h2>Classic Form Demo</h2>
	<form id="form1" action="thanks.php" enctype="multipart/form-data" method="post">
		<p>This demo shows how SWFUpload might be combined with an HTML form.  It also demonstrates graceful degradation (using the graceful degradation plugin).
			This demo also demonstrates the use of the server_data parameter.  This demo requires Flash Player 9+</p>
		<div class="fieldset">
			<span class="legend">Submit your Application</span>
			<table style="vertical-align:top;">
				<tr>
					<td><label for="lastname">Last Name:</label></td>
					<td><input name="lastname" id="lastname" type="text" style="width: 200px" /></td>
				</tr>
				<tr>
					<td><label for="firstname">First Name:</label></td>
					<td><input name="firstname" id="firstname" type="text" style="width: 200px" /></td>
				</tr>
				<tr>
					<td><label for="education">Education:</label></td>
					<td><textarea name="education"  id="education" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea></td>
				</tr>
				<tr>
					<td><label for="txtFileName">Resume:</label></td>
					<td>
						<div>
							<div>
								<input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" />
								<span id="spanButtonPlaceholder"></span>
								(10 MB max)
							</div>
							<div class="flash" id="fsUploadProgress">
								<!-- This is where the file progress gets shown.  SWFUpload doesn't update the UI directly.
											The Handlers (in handlers.js) process the upload events and make the UI updates -->
							</div>
							<input type="hidden" name="hidFileID" id="hidFileID" value="" />
							<!-- This is where the file ID is stored after SWFUpload uploads the file and gets the ID back from upload.php -->
						</div>
					</td>
				</tr>
				<tr>
					<td><label for="references">References:</label></td>
					<td><textarea name="references" id="references" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea></td>
				</tr>
			</table>
			<br />
			<input type="submit" value="Submit Application" id="btnSubmit" />
		</div>
	</form>
</div>
</body>
</html>
3,编写并配置servlet,servlet大部分是网上一朋友写的,我只是按自己的需求修改了一下

public class UploadImg extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("upload file begin");
		//接收参数
				StringBuffer path=new StringBuffer("/uploadfiles/");
				String user = request.getParameter("user");
				String product = request.getParameter("p");
				if(null == user){
					System.out.println("用户为空");
					return;
				}
				if(null == product){
					System.out.println("产品为空");
					return;
				}
				if(product.equals("x")){
					path.append("xiaoxuntong/"+user);
				}else{
					System.out.println("当前没有该产品");
					return;
				}
				String realpath = request.getSession().getServletContext().getRealPath(path.toString());
				System.out.println("_________path:"+realpath);
			
				List<FileEntity> fileList;
				fileList = (List)request.getAttribute("fileList");
				if(fileList==null)
					fileList = new ArrayList<FileEntity>();
				
				//接收上传文件
				String uploadSign = request.getParameter("upload");
				  
				  uploadSign = "1";
				  //上传操作
				  if(null != uploadSign && !"".equals(uploadSign)){
					  FileItemFactory factory = new DiskFileItemFactory();
					  ServletFileUpload upload = new ServletFileUpload(factory);
					  //upload.setHeaderEncoding("UTF-8");
					  try{
						  List items = upload.parseRequest(request);
						  if(null != items){
							  Iterator itr = items.iterator();
							  int i = 0;
							  while(itr.hasNext()){
								  FileItem item = (FileItem)itr.next();
								  FileEntity file = new FileEntity();//
								  if(item.isFormField()){
									  continue;
								  }else{
									  //可修改上传后的文件命名格式
									  SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");//以当前精确到秒的日期为上传的文件的文件名
									  SimpleDateFormat sdd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
									  String type = item.getName().split("\\.")[1];//获取文件类型
									  
									  System.out.println("文件名称:"+item.getName());
									  System.out.println("从GBK转到UTF-8输出:"+new String(item.getName().getBytes("GBK"),"UTF-8"));
									  String fileName=sdf.format(new Date())+"."+type;
									  File savedFile = new File(realpath,fileName);
									  File luFile = new File(realpath);
									  if(!luFile.exists())luFile.mkdirs();
									  //把文件放到列表中,在前台显示
									  System.out.println("服务器上对应的文件名称:"+sdf.format(new Date())+"."+type);
									  System.out.println("完整路径:"+realpath+"/"+sdf.format(new Date())+"."+type);
									  file.setId(sdf.format(new Date()));
									  file.setDate(sdd.format(new Date()));
									  file.setFilename(fileName);
									  file.setFilepath(realpath+"/"+sdf.format(new Date())+"."+type);
									  file.setFilesize(item.getSize()+"");
									  file.setFiletype(type);
									  file.setMark("0");
									  fileList.add(file);
									  
									  item.write(savedFile);
								  }
							  }
						  }
					  }catch(Exception e){
						  e.printStackTrace();
					  }
				  }
				
				
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				if(fileList!=null){
					for(int i=0;i<fileList.size();i++){
						FileEntity file = (FileEntity)fileList.get(i);
                                                 //输出文件的绝对路径
                                               out.println(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+request.getContextPath()+path.toString()+"/"+file.getFilename());
					}
				}
	}

结束!

本实例采用的是Uploadify上传插件,.NET程序,源程序是从网上找的,但是有Bug,已经修改好,并标有部分注释。绝对好用,支持单文件、多文件上传,支持大文件上传,已经过多方面测试,保证好用。 以下附上Uploadify部分常用的参数介绍,要看全部的就去看其API文件了,一般在下载的包里都有。  uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后弹出打开文件对话框,默认值:uploadify.swf。   script : 后台处理程序的相对路径 。默认值:uploadify.php   checkScript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径   fileDataName :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata   method : 提交方式Post 或Get 默认为Post   scriptAccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain   folder : 上传文件存放的目录 。   queueID : 文件队列的ID,该ID与存放文件队列的div的ID一致。   queueSizeLimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。   multi : 设置为true时可以上传多个文件。   auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。   fileDesc : 这个属性值必须设置fileExt属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileDesc为“请选择rar doc pdf文件”,打开文件选择框效果如下图:   fileExt : 设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。   sizeLimit : 上传文件的大小限制 。   simUploadLimit : 允许同时上传的个数 默认值:1 。   buttonText : 浏览按钮的文本,默认值:BROWSE 。   buttonImg : 浏览按钮的图片的路径 。   hideButton : 设置为true则隐藏浏览按钮的图片 。   rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。   width : 设置浏览按钮的宽度 ,默认值:110。   height : 设置浏览按钮的高度 ,默认值:30。   wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。   cancelImg :选择文件到文件队列中后的每一个文件上的关闭按钮图标 Uploadify还自带了很多参数及有用的方法和回调函数,都在API里,虽然是全英文的,但很容易看懂,这里就不说了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值