文件上传:
jsp:
<form id="contractManageEntry" name="contractManageEntry" rel="contractManageEntry" method="post">
<table class="input">
<tr id="handle_0">
<th>文件</th>
<td colspan="3" id="addTd">
<div id="addDiv">
<a id="addFile" href="javascript:void(0);" class="button" >添加文件</a>
<br id="addBr"/>
</div>
<s:iterator value="contractManageEntryBean.contractDocumentLists" status="picUrl">
<div id="div<s:property value='%{#picUrl.index}'/>">
<a id="dialogPreview class="button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" href="javascript:void(0);">
<span class="ui-button-text">预览</span></a>
<a id="del<s:property value='%{#picUrl.index}'/>" href="javascript:void(0);" class="button" οnclick="del(<s:property value='%{#picUrl.index}'/>)">删除</a>
<a id="downLoad<s:property value='%{#picUrl.index}'/>" href="javascript:void(0);" class="button" >下载</a>
s:textfield id="pic%{#picUrl.index}" name="contractManageEntryBean.contractDocumentLists[%{#picUrl.index}]" cssClass="inputtext w-100p required" style="width:200px;" disabled="true" />
<br id="br<s:property value='%{#picUrl.index}'/>">
</div>
</s:iterator>
</td>
</tr>
<tr id="handle_1">
<td colspan="4" class="submit">
<a id="save" href="javascript:void(0);" class="button">保存</a>
<pre name="code" class="html"> </td>
</tr>
</form>
js:
//添加文件处理
$("#addFile").click(function(){
$str="";
$str+="<div id='div"+index+"'>";
$str+="<input id='del"+index+"' class='button ui-button ui-widget ui-state-default ui-corner-all' type='submit' value='删除' role='button' οnclick='del("+index+")'></input>";
$str+=" ";
$str+="<input id='pic"+index+"' class='inputtext' type='file' value='' name='contractManageEntryBean.contractDocumentLists["+index+"]'></input>";
$str+="<br id='br"+index+"'>";
$str+="</div>";
$("#addTd").append($str);
}
});
//文件删除处理
function del(index) {
count = count-1;
$('#div'+index).remove();
};
//保存
var domForm = $('#contractManageEntry')[0];
$(this).loadPageFile(domForm,'contractManageEntrySubmit.action',"保存成功!");
jQuery.fn.loadPageFile = function(form,action,message){
$('.dialog').dialog("destroy").remove();
$.ajaxFileUpload({
url: $('#baseUrl').val() + action,
type: 'post',
dataType: 'json',
form: form,
complete: function() {
$('.qtip').qtip("destroy", true);
},
success: function(data, status) {
var param;
//设置错误信息提示
$("#dialog_message").dialog({
title: "消息",
width: 320,
height: 160,
autoOpen: false,
modal: true,
buttons: [{text: "确定", click: function(){
$(this).dialog("close");
}}],
close: function(){$(this).find("input").val("");}
}).html("<p>"+message+"</p>").dialog('open');
},
error: function() {
$('#contentInner').html('网络繁忙,请稍后再试!');
window.onresize();
}
});
}
});
<pre name="code" class="javascript"> //下载函数
function addDownLoadClick(){
$("a[id^='dialogDownLoad']").click(function(){
var browser;
if (navigator.userAgent.indexOf("MSIE")!=-1) {
browser = "IE";
} else {
browser = "other";
}
var id = this.id;
var index = id.replace("dialogDownLoad","");
var param = "contractAuditEntryBean.index="+ index+ "&contractAuditEntryBean.contractId="+ $("#contractId").val()+ "&contractAuditEntryBean.browser="+ browser;
this.href = $(this).downloadAction(param,"contractAuditEntryDownloadFile");
return true;
});
}
//预览函数
function addPreviewClick(){
$("a[id^='dialogPreview']").click(function(){
var id = this.id;
var index = id.replace("dialogPreview","");
var param = "contractAuditEntryBean.index="+ index+ "&contractAuditEntryBean.contractId="+ $("#contractId").val();
ajaxSubmit('post','contractAuditEntryPreview.action', param, function(data){
var result=eval("("+data+")");
if(result.value=="true"){
window.open(result.filePath);
}else{
//设置错误信息提示
$("#dialog_message").dialog({
title: "消息",
width: 320,
height: 160,
autoOpen: false,
modal: true,
buttons: [{text: "确定", click: function(){$(this).dialog("close");}}],
close: function(){$(this).find("input").val("");}
}).html("<p>" + result.message + "</p>").dialog('open');
}
},null);
return true;
});
}
struts.xml:
<action name="contractManageEntrySubmit" class="contractManageEntryAction" method="execute">
</action>
<action name="contractAuditEntryDownloadFile" class="contractAuditEntryAction" method="download">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="inputName">fileStream</param>
<param name="bufferSize">1024</param>
</result>
</action>
<action name="contractAuditEntryPreview" class="contractAuditEntryAction" method="preview">
<result type="json">
<param name="root">checkResult</param>
</result>
</action>
action:
/**
* 保存
*/
@Override
public String execute() throws Exception {
this.getList();
String userId = (String) this.getSession().get(Constants.SESSION_USER_ID);
contractManageEntryService.saveContractManage( this.contractManageEntryBean,userId);
return null;
}
//下载
// 文件名
private String fileName;
private InputStream fileStream;
public String download() throws Exception {
contractManageEntryService.downLoad(contractManageEntryBean);
String fileNameList[] = contractManageEntryBean.getContractDocumentName().split(";");
String filePathList[] = contractManageEntryBean.getContractDocumentPath().split(";");
this.fileName = fileNameList[contractManageEntryBean.getIndex()];
// IE的情况
if (StringUtils.equals(contractManageEntryBean.getBrowser(), "IE")) {
this.fileName = URLEncoder.encode(fileName, "UTF-8");
// 其他浏览器的情况
} else {
this.fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
String filePath = filePathList[contractManageEntryBean.getIndex()];
fileStream = ServletActionContext.getServletContext().getResourceAsStream(filePath) ;
return SUCCESS;
}
/**
* 预览
*/
public String preview() throws Throwable {
this.checkResult=contractAuditEntryService.preview(contractAuditEntryBean);
// 消息的设置
this.setMessage(this.contractAuditEntryService.getMessage());
return SUCCESS;
}
Service实现类:
/**
* 保存文件
*/
public void saveContractManage(ContractManageEntry contractManageEntry,String userId) {
//Session session = this.getSession();
//Criteria criteria = session.createCriteria(Contract.class);
//criteria.add(Restrictions.eq("contractId", contractManageEntry.getContractId()));
//Contract contract = (Contract) criteria.uniqueResult();
// 文件操作
String filePath = "";
String fileName = "";
// 删除服务器上被删除的文件
String realPath = ServletActionContext.getServletContext().getRealPath("");
if (!StringUtils.isEmpty(contract.getContractDocumentPath())) {
String contractDocumentList[] = contract.getContractDocumentPath().split(";");
String contractDocumentNameList[] = contract.getContractDocumentName().split(";");
String fileNameList[] = contractManageEntry.getPicFileName().split(";");
try {
for (int i=0; i<contractDocumentList.length ; i++) {
if (StringUtils.equals(fileNameList[i], "undefined")) {
// 删除文件
File file = new File(realPath,contractDocumentList[i]);
file.delete();
} else {
filePath+=contractDocumentList[i]+";";
fileName+=contractDocumentNameList[i]+";";
}
}
} catch (Exception e) {
//
} finally {
//
}
}
// 上传新文件
String fileNameList[] = contractManageEntry.getPicFileName().split(";");
try {
// 文件保存路径
File dstFile = new File(realPath, this.FINAL_FOLDER_PATH.concat(userId));
if (dstFile != null && !dstFile.exists()) {
// 创建文件夹
dstFile.mkdirs();
}
for(int i = contractManageEntry.getFielIndex(); i < contractManageEntry.getContractDocumentLists().size(); i++){
if (contractManageEntry.getContractDocumentLists().get(i) != null) {
File tempFile = contractManageEntry.getContractDocumentLists().get(i);
if(tempFile.exists()) {
// 系统时间
Date sysDate = DateUtil.getNow();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
String sysDateStr = sdf.format(sysDate);
String fileType = fileNameList[i].split("[.]")[fileNameList[i].split("[.]").length-1];
String newFileName = sysDateStr.concat(i+"").concat(".").concat(fileType);
File finalFile = new File(realPath, this.FINAL_FOLDER_PATH.concat(userId).concat("/").concat(newFileName));
// 复制文件
FileUtils.copyFile(tempFile, finalFile);
filePath+=this.FINAL_FOLDER_PATH.concat(userId).concat("/").concat(newFileName)+";";
fileName+=fileNameList[i].split("\\\\")[fileNameList[i].split("\\\\").length-1]+";";
}
}
}
} catch (Exception e) {
//
} finally {
//
}
//BeanMapper.copy(contractManageEntry, contract);
//if(StringUtils.equals(contractManageEntry.getContractStatus(), ContractStatus.PASS_MODIFY.getValue())){
//contract.setContractStatus(ContractStatus.PASS_MODIFY.getValue());
//contract.setAuditingLevel("0");
//} else {
//contract.setContractStatus(ContractStatus.WAITING.getValue());
//contract.setAuditingLevel("1");
//}
//contract.setContractDocumentName(fileName);
//contract.setContractDocumentPath(filePath);
//contract.setContractUndertakeUnitOpinion(contractManageEntry.getHiddenContractUndertakeUnitOpinion());
//contract.setUpdateUser(userId);
//contract.setUpdateTime(new Date());
//session.update(contract);
}
/**
* 下载文件
*/
public void downLoad(ContractManageEntry contractManageEntry){
Session session = this.getSession();
Contract contract = (Contract)session.get(Contract.class,contractManageEntry.getContractId());
BeanMapper.copy(contract, contractManageEntry);
}
/**
* 预览
*/
// @SuppressWarnings("rawtypes")
public String preview(ContractAuditEntry contractAuditEntry) throws Throwable {
Session session = this.getSession();
//返回结果设置
Map<String, String> listMap=new HashMap<String, String>();
//转换结果类型
JsonMapper jsonMapper = new JsonMapper();
listMap.put("value", "true");
Contract contract = (Contract)session.get(Contract.class,contractAuditEntry.getContractId());
BeanMapper.copy(contract, contractAuditEntry);
String filePathList[] = contract.getContractDocumentPath().split(";");
String filePath = filePathList[contractAuditEntry.getIndex()];
String xmlPath = previewDoc(filePath);
listMap.put("filePath",xmlPath);
return jsonMapper.toJson(listMap);
}
/**
* 预览doc
*/
public String previewDoc(String path) throws Throwable {
String realPath = ServletActionContext.getServletContext().getRealPath("");
// 系统时间
Date sysDate = DateUtil.getNow();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
String sysDateStr = sdf.format(sysDate);
String htmlFilePath = PREVIEW_FOLDER_PATH2+sysDateStr+".html";
// 启动word应用程序(Microsoft Office Word 2003)
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
// 设置word应用程序不可见
app.setProperty("Visible", new Variant(false));
// documents表示word程序的所有文档窗口,(word是多文档应用程序)
Dispatch docs = app.getProperty("Documents").toDispatch();
// 打开要转换的word文件
Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
new Object[] { realPath + "/" +path, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
// 作为html格式保存到临时文件
FileUtils.write(new File(realPath + PREVIEW_FOLDER_PATH,sysDateStr+".html"), "","gb2312");
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
realPath + "/" + htmlFilePath, new Variant(8) }, new int[1]);
// 关闭word文件
Dispatch.call(doc, "Close", new Variant(false));
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭word应用程序
app.invoke("Quit", new Variant[] {});
}
return htmlFilePath;
}