html页面
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>点击上传</title>
<script src="js/jquery-1.11.1.js"></script>
<script src="js/ajaxfileupload.js"></script>
<script>
function fileSelect(){
var e=arguments.callee.caller.arguments[0]||window.event;
var files=e.target.files;//要上传的文件列表对象
var reg = /image\/.*/i; //文件格式验证
var p=document.getElementById(‘Preview‘);
var ul=document.getElementById(‘Errors‘);
var myp=document.getElementById(‘myprogress‘);
for(var i=0,f;f=files[i];i++){
if(!f.type.match(reg)) {
//设置错误信息
var li=document.createElement(‘li‘);
li.innerHTML=‘<li>‘+f.name +‘不是图片文件.</li>‘;
ul.appendChild(li);
continue;
}else{
var reader = new FileReader();
//文件成功读取完成时触发
reader.onload=(function(file){
return function(e){
var span =document.createElement(‘span‘);
span.innerHTML=‘<img src="‘+this.result+‘" alt="‘+file.name+‘" title="‘+file.name+‘" class="mypic"/>‘;
p.insertBefore(span,null);
};
})(f);
reader.onprogress=function(e){
//更新进度条
myprogress.value=(e.loaded/e.total)*100;
}
reader.onloadend=function(e){
$("#showInfo").fadeIn("show",function(){
$("#showInfo").fadeOut(2000);
});
}
/*
onerror
出错时触发
onload
文件读取成功完成时触发
onloadend
读取完成触发,无论成功或失败
onloadstart
读取开始时触发
onprogress
读取中
*/
//读取文件内容
reader.readAsDataURL(f);
}
}
}
$(function(){
if(window.File && window.FileList && window.FileReader && window.Blob){
$("#Files").change(function(){
fileSelect();
});
}else{
document.write(‘您的浏览器不支持File Api‘);
}
});
function uploadInfo(){
$.ajaxFileUpload({
url:"uploadServlet?uname=navy", //图片处理地址
secureuri:false,
fileElementId:"Files", //图片文本框的id
dataType:"json",
success:function(data,status){ //成功响应
if(parseInt(data)==1){
alert("上传图片成功....");
}else{
alert("上传图片失败....");
}
},
error:function(data, status, e){ //失败响应
alert(data + " == " + status + "==" + e);
}
});
}
</script>
<style>
.mypic{
width:100px;
height:120px;
margin-left:10px;
border:1px solid #F60;
}
progress{
width:800px;
height:30px;
}
#showInfo{
position:absolute;
top:200px;
left:600px;
width:150px;
border:1px solid #ccc;
padding:2px 0px 2px 10px;
display:none;
}
</style>
</head>
<body>
<form action="uploadServlet?uname=navy" enctype="multipart/form-data" method="post" id="myloadphotoform">
<input type="file" multiple id="Files" accept="image/gif,image/jpeg" name="fileField"/>
<input type="button" class="btn" value="上传" onclick="uploadInfo()" />
</form>
<span id="phototals"></span>
<ul id="Errors">
</ul>
<div id="Preview">
</div>
<progress max="100" id="myprogress" value="0"></progress>
<p id="showInfo">图片加载完成...</p>
</body>
</html>
Servlet代码
package com.yc.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import com.yc.utils.UploadUtil;
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
private PrintWriter out;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
out=response.getWriter();
uploadPhoto(request,response);
}
private void uploadPhoto(HttpServletRequest request,HttpServletResponse response) {
String uname=request.getParameter("uname");
try {
uname=URLDecoder.decode(uname,"UTF-8");
UploadUtil upload=new UploadUtil();
PageContext pageContext=JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
Map<String,String> map=upload.upload(pageContext);
String path=map.get("pic");
System.out.println(path);
out.println(1);
out.flush();
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
UploadUtils代码
package com.yc.utils;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.servlet.jsp.PageContext;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
public class UploadUtil {
private static final String PATH="../dataInfo"; //保存图片的文件夹
private static final String ALLOWED="gif,jpg,jpeg,png"; //可以上次的文件类型
private static final String DENIED="exe,bat,jsp,html,com"; //不允许上次的文件类型
private static final int TOTALMAXSIZE=20*1024*1024; //最多上传的大小
private static final int SINGEMAXSIZE=1024*1024; //单个文件的最大大小
private String fname; //文件名
@SuppressWarnings("unchecked")
public Map<String,String> upload(PageContext pagecontext) throws Exception{
Map<String,String> map=new HashMap<String,String>();
SmartUpload su=new SmartUpload();
//初始化
su.initialize(pagecontext);
//设置参数
su.setMaxFileSize(SINGEMAXSIZE);
su.setTotalMaxFileSize(TOTALMAXSIZE);
su.setAllowedFilesList(ALLOWED);
su.setDeniedFilesList(DENIED);
su.setCharset("utf-8");
su.upload(); //调用SmartUpload里面的upload方法开始上传
//Request request=su.getRequest(); //重SmartUpload中获取用户请求的信息
//map.put("tid",request.getParameter("ntid"));
if(su.getFiles()!=null&&su.getFiles().getCount()>0){ //说明请求中含有文件
Files fs=su.getFiles(); //取出请求中的所有文件信息
Collection<File> col=fs.getCollection();
String extname; //文件的扩展名
String realpath; //存入服务器的路径 服务器所在的地址:8080/项目名/PATH/文件名
String path="";
for(File f:col){ //循环取出每一个上传的文件
if( ! f.isMissing() ){ //判断上传的文件有没有丢失
//获取上传的文件的后缀名
extname=f.getFileExt();
fname=new Date().getTime()+""+new Random().nextInt(1000)+"."+extname;//给上传的文件重新命名,以免重复 42342355535
realpath=PATH+"/"+fname;
//把上传的图片写入服务器
f.saveAs(realpath,SmartUpload.SAVE_VIRTUAL);
path+=realpath+",";
}
}
if(path.indexOf(",")>0){
path=path.substring(0,path.lastIndexOf(","));
}
map.put("pic",path); //往数据库写的路径
}else{
map.put("pic",null); //往数据库写的路径
}
return map;
}
}