多照片上传插件代码.docx

上传人:b****6 文档编号:8450045 上传时间:2023-01-31 格式:DOCX 页数:16 大小:20.80KB
下载 相关 举报
多照片上传插件代码.docx_第1页
第1页 / 共16页
多照片上传插件代码.docx_第2页
第2页 / 共16页
多照片上传插件代码.docx_第3页
第3页 / 共16页
多照片上传插件代码.docx_第4页
第4页 / 共16页
多照片上传插件代码.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

多照片上传插件代码.docx

《多照片上传插件代码.docx》由会员分享,可在线阅读,更多相关《多照片上传插件代码.docx(16页珍藏版)》请在冰豆网上搜索。

多照片上传插件代码.docx

多照片上传插件代码

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;i

Strings_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;'>

+ary[i].name

+"'width='160px'height='200px'>

");

$("#J_div").append(

"

+ary[i].name

+"'width='160px'height='200px'>

");

}

$(".close").click(function(){

varimg=$(this).parent().next().children().val();

$.post(

"delImg",

{method:

'post',

img:

img},

"xml");

$(this).parent().next().remove();

$(this).parent().remove();

});

}

});

});

.img_boxx{position:

relative;width:

200px;height:

135px;float:

left;display:

inline;padding:

05px;margin-bottom:

10px;}

.img_boxxspan{background:

#fff;position:

absolute;top:

0px;right:

5px;width:

15px;height:

15px;display:

block;}

.img_remove{cursor:

pointer;}

---->

 

Uploadify.css---------样式

/*

Uploadify

Copyright(c)2012ReactiveApps,RonnieGarcia

ReleasedundertheMITLicense

//www.opensource.org/licenses/mit-license.php>

*/

.uploadify{

position:

relative;

margin-bottom:

1em;

}

.uploadify-button{

background-color:

#50

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高中教育 > 高考

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1