Struts2结合Jquery.uploadify上传插件的应用

这几天一直在搞文件上传,刚开始用struts自带的上传标签进行处理,感觉不是很完美,因为每次只能上传一个文件,自己操作了几次,就感觉不是很方面。然后看到网上说可以动态生成input输入框,这样一次就可以多上传几个附件了,改了之后,感觉还是不是很完美,因为每次需要手工点击“添加附件”的按钮后才可以自动生成一个input文件选择框。然后就在网上继续找完美的解决方案,终于发现Struts+Jquery.uploadify可以完美解决这个问题,而且效果也很漂亮。


jsp页面代码:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page pageEncoding="UTF-8"%>
<html>
<head>
<title>上传/下发文件(国内)列表 </title>
<%@include file="/base/inc/commons.inc"%>
<link href="<%=contextPath%>/base/css/queryForm.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="<%=contextPath%>/mgr/comexport/reportUpload4.js"></script>
<script type="text/javascript" src="<%=contextPath%>/base/js/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="<%=contextPath%>/base/js/swfobject/swfobject.js"></script>
<link rel="stylesheet" type="text/css" href="<%=contextPath%>/base/js/uploadify/uploadify.css"/>
<script type="text/javascript">
$(function() {
var i=0;
var errMsg="";
$("#file").uploadify({
height : 20,
swf : '<%=contextPath%>/base/js/uploadify/uploadify.swf',
uploader : '<%=contextPath%>/localnet/comexport/rReportUpload/fileUplodMethod.action',
width : 100,
buttonImg : '<%=contextPath%>/base/css/images/default/tree/folder-open.gif',
buttonText : '添加附件 ',
auto : false,
cancelImage : '<%=contextPath%>/base/js/uploadify/cancel.png',
fileObjName :'file',
fileSizeLimit : '1024MB',
fileTypeExts : '*.xls;*.XLS;*.rar;*.RAR',
fileTypeDesc : '请选择xls或rar格式的文件!',
method : 'post',
queueID : 'fileQueue',
queueSizeLimit: 999,
progressData : 'all',
removeCompleted : true,
removeTimeout : 1,
multi : true,
formData : {'random':''},
dataType : 'json',
progressData : 'percentage',
onUploadStart : function(file) {
$("#file").uploadify("settings", "formData", {'random':Math.random()});
},
onComplete: function (event, queueID, fileObj, response, data) {

$('<li></li>').appendTo('.files').text(response +" 00000000");
},
onSelectError : function(file,errorCode,errorMsg)
{
alert( '文件' + file.name+'上传失败!');
},
onCancel: function(event, queueID, fileObj){
//alert("取消了" + fileObj.name);
},
onUploadSuccess : function(file,data,response) {
if(response){
var obj=eval("("+data+")");
if(obj.success){
i=i+1;
}
else{
errMsg+="文件:"+file.name +" 上传失败!\n";
}
}else{
alert("上传失败,请联系管理员!");
}
},
onQueueComplete:function(queueData){
if(errMsg !=""){
alert(errMsg);
$('#gridContainer').gridOptions( {newp : 1}).gridReload();
}else{
alert("上传成功!");
$('#gridContainer').gridOptions( {newp : 1}).gridReload();
}
/* if(queueData.uploadsSuccessful==i){
if(queueData.uploadsErrored==0){
alert("上传成功!");
$('#gridContainer').gridOptions( {newp : 1}).gridReload();
}else{
alert("上传失败!");
}
}else{
alert("上传失败!");
} */
}
});
});

</script>

<style type="text/css">
a
{
color: #707070;
font-family: "Tahoma";
font-size: 13.5px;
}
img
{
color:#CEE0FF;
font-family: "Tahoma";
font-size: 13px;
/* background-color:#CEE0FF; */
width: 13.5px;
height: 13.5px;
}
</style>
</head>
<body>
<div id="headerDiv">
<div class="queryDiv">
<fieldset>
<div class="queryTableDiv">
<table class="table_seach_div" id="query_bar_div">
<tbody>
<td colspan="3">
<input type="file" name="file" id="file" />
<div id="fileQueue"></div>


[url=javascript:$('#file').uploadify('upload','*')]<img src="<%=contextPath%>/base/css/images/default/grid/col-move-bottom.gif"> 开始上传[/url]

[url=javascript:$('#file').uploadify('cancel','*')]<img src="<%=contextPath%>/base/css/images/default/tree/drop-no.gif" > 取消所有上传[/url]


<ol class=files></ol>
</td>
</tbody>
</table>
</div>
</fieldset>
</div>
</div>
<div id="gridContainer"></div>
</body>
</html>


后台JavaAction代码:


@SuppressWarnings("serial")
@ParentPackage("ppmweb")
public class RReportUploadAction extends CommonAction {

//@Qualifier("rReportUploadService")
@Autowired
private IRReportUploadService rReportUploadService;
private RReportUploadBean rReportUploadBean;

private File[] file;
private String[] fileFileName;
private String[] fileContentType;

/* private File[] file;
private String[] fileFileName;
private String[] fileContentType;*/

//主键数组,用于删除
public String[] reportNames;
public String[] upTimes;

private static final int BUFFER_SIZE=16*1024;


@Action(value = "/localnet/comexport/rReportUpload/queryList")
public String queryList()throws Exception {
queryParam = ActionUtil.prepareQuery(rReportUploadBean, request);
if(rReportUploadBean ==null){
rReportUploadBean=new RReportUploadBean();
}
rReportUploadBean.setExtraOrderColumns("up_time desc");
ServiceResult<RReportUploadBean> list=rReportUploadService.queryList(rReportUploadBean, queryParam.getRowBounds());
// 导出操作
if (excelBean != null) {
File f=File.createTempFile("exp", "xls");
FileOutputStream outputStream = new FileOutputStream(f);
ExcelUtil.createExcel(list.getResult(), excelBean, outputStream);
ServiceResult<RReportUploadBean> context = super.getContext();
context.setUserObject(f.getAbsolutePath());
super.writeJson(context);
} else {
//输出到grid
super.write4Grid(list);
}
return NONE;
}

/*
* 文件上传(将文件上传到服务器临时目录/outtemplet/upload)
*/
@Action(value = "/localnet/comexport/rReportUpload/fileUplodMethod")
public String fileUplodMethod(){
String encoding = System.getProperty("sun.jnu.encoding");
ServiceResult<RReportUploadBean> result = super.getContext();
InputStream in=null;
OutputStream out=null;
boolean up=true;
String str="";
if(file !=null && file.length >0){
for (int i = 0; i < file.length; i++) {
try {
System.out.println("上传文件名:"+fileFileName +" ;上传文件的路径为:"+file[i].getAbsolutePath());
File desDirect=new File(ServletActionContext.getServletContext().getRealPath(File.separator+"outtemplet"+File.separator+"upload"+File.separator+new String(fileFileName[i].getBytes("GBK"), encoding)));
//FileUtils.copyFileToDirectory(file, desDirect);
in=new BufferedInputStream(new FileInputStream(file[i]),BUFFER_SIZE);
out=new BufferedOutputStream(new FileOutputStream(desDirect));
byte[] buff=new byte[BUFFER_SIZE];
while(in.read(buff) >0){
out.write(buff);
}

} catch (Exception e) {
up=false;
result.setSuccess(false);
result.setMessage(e.getMessage());
System.out.println("RReportUploadAction.fileUplodMethod() 文件复制出错!");
}finally{
try {
if(null !=in){
in.close();
}
if(null !=out){
out.close();
}
} catch (IOException e) {
System.out.println("关闭文件读写流出错!");
e.printStackTrace();
}
}
if(up){
Date date = new Date();
RReportUploadBean uploadBean = new RReportUploadBean();
uploadBean.setReportName(fileFileName[i]);
uploadBean.setUpTime(date);
uploadBean.setStaffName(getStaffName());
result = rReportUploadService.insertEntity(uploadBean);
if(!result.isSuccess()){
str+=result.getMessage();
}
}
}
}
try {
if(!str.equals("")){
result.setSuccess(false);
result.setMessage(str);
}
super.writeJson(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return NONE;
}


/*
* 文件下发(将文件同步到/gjjs/data/upload目录下)
*/
@Action(value = "/localnet/comexport/rReportUpload/fileDownLoadMethod")
public String fileDownLoadMethod()throws Exception {
String resut="";
ServiceResult<RReportUploadBean> context = super.getContext();
String encoding = System.getProperty("sun.jnu.encoding");
String home=System.getProperty("user.home");
String desDirect="";
if(home.endsWith(File.separator)){
desDirect=home+"data"+File.separator+"upload";
}else {
desDirect=home+File.separator +"data"+File.separator+"upload";
}
System.out.println("打印文件主目录:"+home);
System.out.println("打印移动目标目录:"+desDirect);

SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
if(reportNames !=null && reportNames.length >0 && upTimes !=null && upTimes.length>0){
for (int i = 0; i < reportNames.length; i++) {
//复制文件
String srcFilePath=ServletActionContext.getServletContext().getRealPath(File.separator+"outtemplet"+File.separator+"upload"+File.separator+new String(reportNames[i].getBytes("GBK"), encoding));
File srcFile=new File(srcFilePath);
if(srcFile.exists()){
String resuStr=FileCopyUtil.fileCopyMethod(srcFilePath, desDirect, reportNames[i]);
if(resuStr.equals("")){
RReportUploadBean uploadBean=new RReportUploadBean();
uploadBean.setReportName(reportNames[i]);
uploadBean.setUpTime(sDateFormat.parse(upTimes[i].replace("-", "/")));
uploadBean=rReportUploadService.loadEntity(uploadBean);
if(uploadBean !=null){
uploadBean.setDownTime(new Date());
if(resuStr.equals("")){
//说明复制成功
uploadBean.setDownFlag("1");
}else {
uploadBean.setDownFlag("2"); //复制失败
}
context=rReportUploadService.updateEntity(uploadBean);
if (!context.isSuccess()) {
resut+=reportNames[i]+" 该文件写数据库出错!";
}
}
}else {
System.out.println(reportNames[i] +" 该文件在下发过程中出错!");
}

}else {
System.out.println(reportNames[i]+" 该文件不存在!");
resut+=reportNames[i]+" 该文件不存在!";
continue;
}
}
}else {
context.setMessage("传入参数为空!");
context.setSuccess(false);
}
if(resut.length()>0){
context.setMessage(resut);
context.setSuccess(false);
}else {
context.setMessage("下发成功!");
context.setSuccess(true);
}
writeJson(context);
return NONE;
}



/*
* 跳转到上传/下发界面
*/
@Action(value = "/comexport/rReportUpload/toUploadPage", results = { @Result(name = "success", location = "/mgr/comexport/reportUpload4.jsp") })
public String toUploadPage() {
System.out.println("+++++++跳转到上传/下发界面+++++++++");
return SUCCESS;
}

}



具体的方法,属性,参数的用法可以参考:http://www.cnblogs.com/akingyao/archive/2012/09/05/2671297.html


遗留问题:中文乱码
后台返回json格式的数据后,前台获得obj.message一直是乱码。捣鼓了好长时间也没解决...........


2014-08-14 0:48 @yanggaonanlu.pudongqu.shanghai
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值