AJAX重名验证和JQUERY附件上传,PPT,实例,上传头像,给文件名加时间戳【诗书画唱】


uploadify是JQuery的一个上传插件,实现的效果非常不错,支持同时选择多个附件上传并自带进度条效果,并提供了一系列的回调处理函数。
可到http://www.uploadify.com/download/下载最新的版本,文件名为uploadify.zip。






实例:
重名验证:



package com.jy.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class NameServlet
*/
@WebServlet("/ns")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public NameServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String act = request.getParameter("act");
System.out.println(act);
//判断是否重名
String msg = "";
if("诗书画唱".equals(act)) {
msg = "该账号已被使用";
} else if("".equals(act)){
msg = "请输入账号";
} else {
msg = "该账号可以使用";
}
//将msg回传到jsp页面
response.setCharacterEncoding("utf-8");
response.getWriter().write(msg);
}
}


<%@ page language="java" contentType=
"text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
<title>重名验证</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">
<style type="text/css">
*{
font-size: 50px;
}
</style>
<script type="text/javascript" srcc="js/jquery-1.11.0.js">
</script>
<script type="text/javascript">
$(function(){
$('#act').bind('input',function(){
//获取输入文本框中的内容
var a = $('#act').val();
//console.log(act);
//提交重名验证的请求
$.ajax({
url: 'ns',//重名验证servlet的路径
type: 'POST',//请求的提交方式(全大写)
data: {
act: a
},//需要传递的参数都可以写在data对象中
success: function(data){//回调函数
//获取后台提示信息,将提示信息写到id为msg的div中
$('#msg').html(data);
}
});
});
})
</script>
</head>
<body>
<input type="text" id="act"
placeholder="请输入账号" />
<div id="msg"></div>
</body>
</html>





作业:
实现一个只能上传图片的页面,上传成功以后要在页面上显示这个图片。
















package com.jy.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/us")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
//获取项目的路径
String realPath = request.getServletContext().getRealPath("/");
//E:\JAVA\apache-tomcat-7.0.56\webapps\J190801\
//System.out.println(realPath);
//附件上传的保存路径
String uploadPath = realPath + "upload/";
//如果上传的文件夹不存在,就创建它
File file = new File(uploadPath);
if(!file.exists()) {
file.mkdirs();
}
//执行上传
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
//设置上传的字符编码
upload.setHeaderEncoding("utf-8");
//开始解析request中的file
List<Object>fileList = upload.parseRequest(request);
Iterator<Object> it = fileList.iterator();
//依次处理选择上传的文件
while(it.hasNext()) {
//取出每个文件
Object item = it.next();
//如果item能够成功的转型成DiskFileItem
if(item instanceof DiskFileItem) {
//将item强制转型成DiskFileItem
DiskFileItem fileItem = (DiskFileItem)item;
//如果fileItem是一个input type=file的控件
if(!fileItem.isFormField()) {
//获取选中需要上传文件的文件名,带后缀
String fileName = fileItem.getName();
//设置上传附件的全路径
// ——————
//生成一个时间戳
//获取到当前的日期
Date now = new Date();
//将当前日期转换成时间戳
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");
String stamp = sdf.format(now);
System.out.println("时间戳是:" + stamp);
//UUID:全球唯一标识符
int index = fileName.lastIndexOf('.');
String f1 = fileName.substring(0,index);
System.out.println("文件的前半部分是:" + f1);
String f2 = fileName.substring(index);
System.out.println("文件的后半部分是:" + f2);
//添加时间戳
String fname = f1 + "-" + stamp + f2;
System.out.println("处理以后的文件名是:" + fname);
// ——————
// String fullPath = uploadPath + fileName;
String fullPath = uploadPath + fname;
//执行附件上传
bis = new BufferedInputStream(fileItem.getInputStream());
//将上传的全路径转换成File对象
File f = new File(fullPath);
System.out.println("全路径:"+fullPath);
bos = new BufferedOutputStream(new FileOutputStream(f));
//执行复制
Streams.copy(bis, bos, true);
//将附件上传成功的信息回写到回调函数中
response.setCharacterEncoding("utf-8");
// response.getWriter().write("成功上传的文件名是:" + fname);
response.getWriter().write(fullPath);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}



/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
.uploadify {
position: relative;
margin-bottom: 1em;
}
.uploadify-button {
background-color: #505050;
background-image: linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -o-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -moz-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -webkit-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -ms-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, #505050),
color-stop(1, #707070)
);
background-position: center top;
background-repeat: no-repeat;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
border: 2px solid #808080;
color: #FFF;
font: bold 12px Arial, Helvetica, sans-serif;
text-align: center;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
width: 100%;
}
.uploadify:hover .uploadify-button {
background-color: #606060;
background-image: linear-gradient(top, #606060 0%, #808080 100%);
background-image: -o-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -moz-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -webkit-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -ms-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, #606060),
color-stop(1, #808080)
);
background-position: center bottom;
}
.uploadify-button.disabled {
background-color: #D0D0D0;
color: #808080;
}
.uploadify-queue {
margin-bottom: 1em;
}
.uploadify-queue-item {
background-color: #F5F5F5;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
font: 11px Verdana, Geneva, sans-serif;
margin-top: 5px;
max-width: 350px;
padding: 10px;
}
.uploadify-error {
background-color: #FDE5DD !important;
}
.uploadify-queue-item .cancel a {
background: url('../img/uploadify-cancel.png') 0 0 no-repeat;
float: right;
height: 16px;
text-indent: -9999px;
width: 16px;
}
.uploadify-queue-item.completed {
background-color: #E5E5E5;
}
.uploadify-progress {
background-color: #E5E5E5;
margin-top: 10px;
width: 100%;
}
.uploadify-progress-bar {
background-color: #0099FF;
height: 3px;
width: 1px;
}

<%@ page language="java" contentType="text/html; charset=UTF-8" 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">
<style>
img{height: 100px;width: 100px;
border-radius: 50%;}
</style>
<html>
<head>
<base hreff="<%=basePath%>">
<title>附件上传</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 rel="stylesheet" type="text/css" href="css/uploadify.css">
<script type="text/javascript" srcc="js/jquery-1.11.0.js"></script>
<script type="text/javascript" srcc="js/jquery.uploadify.js"></script>
<script type="text/javascript">
$(function(){
//初始化附件上传界面
$('#uploadify').uploadify({
'auto':true, // 选择文件后自动上传
'swf':'js/uploadify.swf', // 上传flash文件路径
'uploader':'us',//后台处理的请求的url路径
'queueID':'fileQueue',//选中文件的队列放在id为fileQueue的div中
'queueSizeLimit':3,//一次最多上传的文件数
'fileObjName':'aaa', // 后台接受参数名称,后台获取这个参数值的方式:fileItem.getFilename()
'preventCaching':true, // 设置随机参数,防止缓存
'progressData':'percentage', // 显示上传进度百分比
'removeCompleted':false, // 上传后是否自动删除记录
'fileTypeDesc':'jpg,jpeg,png,gif', // 支持的文件格式,写filetypeExts该参数必须写
'fileTypeExts':'*.jpg;*.jpeg;*.png;*.gif', //在打开文件对话框时,仅显示这些后缀名的文件,其他文件看不到,启用本项时需同时声明fileDesc
'multi': true, // 是否支持多文件上传
'uploadLimit':50, // 上传限制
'onCancel':function(){
// 取消上传事件
alert('删除上传');
},
//每一个文件上传成功后触发
'onUploadSuccess' : function(file,data,response) {
//data为后台程序中通过response回写到前台的数据
alert("data的值,上传的文件的绝对路径(全路径):"+data);
//alert("file的值:"+file);
imgDiv= "<img srcc='"+data+"'>";
$("#imgId").append(imgDiv)
},
'onQueueComplete' : function(queueData) {
// 所有文件上传成功后触发
alert('所有的附件上传完毕');
},
'buttonText': '上传' //附件上传按钮显示的内容
});
})
</script>
</head>
<body>
<!-- 需要上传的文件队列 -->
<div id="fileQueue"></div>
<input type="file" id="uploadify" name="uploadify" />
<p>
<a hreff="javascript:$('#uploadify').uploadify('upload');">开始上传</a>
<a hreff="javascript:$('#uploadify').uploadify('cancel');">取消上传</a>
</p>
<div id='imgId'></div>
</body>
</html>





