日期:2014-05-16  浏览次数:20384 次

jsp-jquery-ajaxfileupload插件-异步上传

?

1. 简单的请求页面: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>AJAX上传文件</title>

	<script type="text/javascript" src="<%=basePath %>js/jquery.js"></script>
	<script type="text/javascript" src="<%=basePath %>js/ajaxfileupload.js"></script>
	
	<script type="text/javascript">
		function fileupload(){
			if($("#filePath").val()==""){
				alert("上传文件不能为空!");
				return false;
			}
			$.ajaxFileUpload({
					url:"<%=basePath %>/fileLoad",
					secureuri:false,
					fileElementId:'filePath',
					dataType: 'text/xml',			
					success: function (data) {
						alert("success");
					},error: function (data, status, e){
						alert("fail");
					}
				}
			);
		}
	</script>
  </head>

  <body>
    <input type="file" name="filePath" id="filePath"/>
    <input type="button" name="fileLoad" id="fileLoad" value="上传" onClick="fileupload()"/>
  </body>
</html>
?

?


2. 简单的servlet上传文件处理
// 上传之后的文件保存在这个文件夹下
		String filepath = this.getServletContext().getRealPath("")+java.io.File.separator+"picture"+java.io.File.separator;
		String filename = "";
		String type="";
		ServletInputStream in = request.getInputStream();
		byte[] buf = new byte[4048];
		int len = in.readLine(buf, 0, buf.length);
		String f = new String(buf, 0, len - 1); 
		while ((len = in.readLine(buf, 0, buf.length)) != -1) {
			filename = new String(buf, 0, len);
		    int j = filename.lastIndexOf("\"");
		    int p = filename.lastIndexOf("."); 
		    //文件类型
		    type=filename.substring(p,j);   
		    //文件名称
		    filename = System.currentTimeMillis()+type;  

		    DataOutputStream fileStream = new DataOutputStream(
			new BufferedOutputStream(new FileOutputStream(filepath+ filename))
		    );

		    len = in.readLine(buf, 0, buf.length); 
		    len = in.readLine(buf, 0, buf.length); 
		    while ((len = in.readLine(buf, 0, buf.length)) != -1) {
		        String tempf = new String(buf, 0, len - 1);
		        if (tempf.equals(f) || tempf.equals(f + "--")) {
		            break;    
		        }
		        else{
				 // 写入
		        	 fileStream.write(buf, 0, len);
		        }
		    }
		    fileStream.close();
		}
		PrintWriter out=response.getWriter();
		String result = filename ;
		out.print(result);
		out.close();
		in.close();
?

?

?


1 楼 llshxy 2011-09-14  
很不错,下载后需要改web.xml中的servlet路径。O(∩_∩)O谢谢