多照片上传插件代码.docx
《多照片上传插件代码.docx》由会员分享,可在线阅读,更多相关《多照片上传插件代码.docx(16页珍藏版)》请在冰豆网上搜索。
多照片上传插件代码
FileUploadServlet.java-----实现图片的储存
packagecom.xiaoxing.upload;
importjava.io.File;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.io.UnsupportedEncodingException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Iterator;
importjava.util.List;
importjava.util.UUID;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importmons.fileupload.FileItem;
importmons.fileupload.disk.DiskFileItemFactory;
importmons.fileupload.servlet.ServletFileUpload;
/**
*
ApacheFileupload文件上传(2014-5-3)
*
*1、如果你对本示例感兴趣并想了解更多,欢迎加入Java私塾在线学习社区(329232140)
*
*
*2、针对这个例子小修小改便可移植到你的实际项目中。
*
*/
publicclassFileUploadServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=7579265950932321867L;
//设置文件默认上传目录(如果你没有在web.xml中配置的话)
privateStringuploadDir="c:
/";//文件上传目录
privateStringtempUploadDir="c:
/";//文件临时存放目录(会话销毁后由监听器自动删除)
/*
*(non-Javadoc)
*
*@seejavax.servlet.GenericServlet#init()
*如果在web.xml中配置了文件上传目录则优先使用,判断文件目录是否存在,不存在就创建。
*/
@Override
publicvoidinit()throwsServletException{
//获取本项目所在真实硬盘目录
Stringpath=getClass().getProtectionDomain().getCodeSource()
.getLocation().getPath();
path=path.substring(0,path.indexOf("WEB-INF"));
//判断目标是否存在,不存在就建立
StringuploadDir=path.concat(this.getInitParameter("uploadDir"));
System.out.println("uploadDir:
="+uploadDir);
StringtempUploadDir=path.concat(this.getInitParameter("tempUploadDir"));
System.out.println("tempUploadDir:
="+tempUploadDir);
Filef_uploadDir=newFile(uploadDir);
Filef_tempUploadDir=newFile(tempUploadDir);
if(!
f_uploadDir.exists()){
f_uploadDir.mkdirs();
}
if(!
f_tempUploadDir.exists()){
f_tempUploadDir.mkdirs();
}
//给变量赋值
this.uploadDir=uploadDir;
this.tempUploadDir=tempUploadDir;
}
/*
*(non-Javadoc)
*
*@see
*javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
*,javax.servlet.http.HttpServletResponse)不接收get方式提交的数据,返回上传失败状态码。
*/
@Override
protectedvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)throwsServletException,IOException{
this.setResponse(response);
PrintWriterout=response.getWriter();
out.print("{\"error\":
\"-1\"");//非法提交方式
}
/*
*(non-Javadoc)
*
*@see
*javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
*,javax.servlet.http.HttpServletResponse)上传文件请求都是通常POST提交
*/
@Override
protectedvoiddoPost(HttpServletRequestrequest,
HttpServletResponseresponse)throwsServletException,IOException{
this.setResponse(response);//设置响应类型,以便前端解析
PrintWriterout=response.getWriter();
Stringresult="";
try{
//检查本次是否一个文件上传请求
booleanisMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactoryfactory=newDiskFileItemFactory();//创建一个工厂基于磁盘的文件项
factory.setRepository(newFile(tempUploadDir));//配置储存库(确保安全的临时位置时)
ServletFileUploadupload=newServletFileUpload(factory);//创建一个新的文件上传处理程序
upload.setSizeMax(1024*1024*100);//设置总体要求尺寸限制(建议前后台分别设置,因为前后台用到了不同的插件)
Listitems=upload.parseRequest(request);//解析请求
Iteratoriter=items.iterator();//处理上传的项目
while(iter.hasNext()){//如果是一次性上传多个文件,那这里会分别去保存
FileItemitem=iter.next();
if(!
item.isFormField()){//过滤表单里的非文件类型字段
if(!
"".equals(item.getName())){//过滤非文件类型的input
Strings_name=item.getName();//获得原始文件名
intposition=s_name.lastIndexOf(".");
Strings_fileType=s_name.substring(position,
s_name.length());//获得文件后缀
Stringdate=newSimpleDateFormat("yyyyMMdd")
.format(newDate());
Strings=uploadDir.concat("/").concat(date)
.concat("/");
//这里按日期分目录保存文件
Filesf=newFile(s);
if(!
sf.exists()){
sf.mkdirs();
}
Strings_filePath=s.concat(
UUID.randomUUID().toString()).concat(
s_fileType);
Filepath=newFile(s_filePath);
item.write(path);
result+=s_filePath.concat(",");
}else{
result="";
break;
}
}
}
}else{
result="";
}
Strings_resultJSON=this.jointJSON(result);//拼接返回前端JSON
out.print(s_resultJSON);
}catch(Exceptione){
e.printStackTrace();
}finally{
out.flush();
out.close();
}
}
/**
*拼接JSON,将保存文件的文件名和日期目录返回给前端(前端可能需要这个路径完成其他表单操作,比如将文件路径存放到数据库)
*
*@paramresult
*JSON格式的字符串
*@return
*@throwsUnsupportedEncodingException
*/
privateStringjointJSON(Stringresult)throwsUnsupportedEncodingException{
Stringstr="";
if(!
"".equals(result)){
Stringrs[]=result.split(",");
StringBufferbuffer=newStringBuffer("{\"rows\":
[");
for(inti=0;iStrings_tmpName=rs[i];
s_tmpName=s_tmpName.substring(uploadDir.length(),s_tmpName
.length());
buffer.append("{\"name\":
\"").append(s_tmpName).append("\"},");
}
str=buffer.toString();
str=str.substring(0,str.length()-1).concat("]}");
}else{
str="{\"error\":
\"-2\"";//上传失败
}
returnstr;
}
/**
*设置响应类型ContentType为"application/x-json"
*
*@paramresponse
*/
privatevoidsetResponse(HttpServletResponseresponse){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.setHeader("cache-control","no-cache");
}
}
Web.xml-------配置
xmlversion="1.0"encoding="UTF-8"?
>
xsi="http:
//www.w3.org/2001/XMLSchema-instance"xmlns="xsi:
schemaLocation="id="WebApp_ID"version="2.5">
sd
test_upload.html
专门用来处理上传操作的servlet
FileUploadServlet
com.xiaoxing.upload.FileUploadServlet
文件存放的正式目录,可以自己配置
uploadDir
/upload/images/
文件存放的临时目录,可以自己配置,里的文件由下面配置的监听器自动删除。
tempUploadDir
/upload/temp
DeleteServlet
com.xiaoxing.upload.DeleteServlet
DeleteServlet
/delImg
FileUploadServlet
/upload
临时文件资源清理,工具包自带,不用我们来写
mons.fileupload.servlet.FileCleanerCleanup
test_upload.html-------前台页面
DOCTYPEhtml>
jQueryUploadify+ApacheFileupload异步上传文件示例(2014-5-3)
$(function(){
$('#fileupload').uploadify({
'method':
'post',
'buttonText':
'flash上传文件',
'fileSizeLimit':
'2048KB',
'fileTypeExts':
'*.gif;*.jpg;*.png',
'swf':
'uploadify.swf',
'uploader':
'upload',//这是上传图片的路径,也就是我在web.xml里配置的servlet
'onUploadSuccess':
function(file,data,response){//图片上传成功后返回数据在这里处理
varary=eval("("+data+")").rows;
vardata=$("#data").val()+1;
$("#data").val(data);
for(vari=0;i$("#J_div").append(
"relative;width:
160px;height:
200px;float:
left;margin-right:
10px;'>absolute;top:
8px;right:
8px;cursor:
pointer;'>