#set($layout = "$!{path.getThemePath('myfront_theme')}/common/layout.vm")
<link rel="stylesheet" href="$!{base}/js/validate/validator.css" type="text/css" />
<script type="text/javascript" src="${base}/js/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="$!{base}/js/validate/validator.css" type="text/css" /> <script type="text/javascript" src="$!{base}/js/libs/jquery.form.js"></script> <script type="text/javascript" src="$!{base}/js/validate/jquery.validate.js"></script> <script type="text/javascript" src="$!{base}/js/validate/jquery.validate.extend.js"></script> <script type="text/javascript" src="$!{base}/js/validate/jquery.validate.methods.js"></script> <script type="text/javascript" src="${base}/js/script/ajaxfileupload.js"></script> <script type="text/javascript"> //表单校验 jQuery(document).ready(function(){ var v = jQuery("#myForm").validate({ rules:{ buildingId:{ required:true },paymentId:{ required:true },
file:{ required:true, accept:"xls" } //增加对上传文件的验证约束, file必须为 type='file' name="file" 必须为 name="file"
}, messages:{ buildingId: { required: "请选择" },paymentId: { required: "请选择缴费项目类型" },
file: { required: "请选择模板文件", accept: "选择模板文件格式只支持xls" } },
}, submitHandler: function () { saveSubmit(); } }); });//结束表单校验 var buildingId; var paymentId; //表单ajax提交测试方法. function saveSubmit() { jQuery('#submitBtnsusu').attr('disabled','true');//屏蔽提交按钮 var flag = false; jQuery.ajax({ type: "POST", url: '$!{base}/mallfront/wymanegement/saveExcelInfo.action', data: {"buildingId":buildingId,"paymentId":paymentId,"uploadDir":jQuery('#uploadDir').val()}, dataType:'json', success:function(result){ if(!result.success){ alert(result.mssage); $('#submitBtnsusu').attr('disabled','true'); }else{ alert(result.mssage); $('#submitBtnsusu').attr('disabled','false'); //执行其他方法. //指向缴费信息列表页 window.location.href="$!{base}/mallfront/wymanegement/wypayrecordinfo.jhtml"; } } }); } //选择文件之后执行上传,把file对象传到action中的file对象. function upload(obj) { //判断是否有文件选择. if ($(obj).val().length > 0) { jQuery.ajaxFileUpload({ url: '$!{base}/mallfront/wymanegement/executeImport.action', fileElementId: $(obj).attr('id'), success: function (data, status) { var url=$(data).find("pre").html().replace("\\", "");//替换斜杠 //给新生产的文件路径赋值 $("#uploadDir").val(url.replace(/"/g, "")); }, error: function (data, status, e) { console.log(e); alert(e); } }); return false; } } //获取小区下拉 function getBuildId(){ buildingId = jQuery.trim($("#buildingId option:selected").val());//小区ID } //获取缴费项目Id function getPaymentId(){ paymentId = jQuery.trim($("#paymentId option:selected").val());//缴费类型ID } </script> <div class="container"> #parse("$!{path.getThemePath('mallfront_theme')}/common/property_left.vm") <div class="business_r" id="tab"> <div class="tabList"> <ul class="fl"> </ul> </div> <div class="blank"></div> <div class="tabCon"> <form id="myForm" action="executeImport.action" method="post"> <table class="tab" width="100%" border="0" cellspacing="1" cellpadding="0"> <tbody> <tr> <td class="tab-content1"> <label><span class="red">*</span>名称 #set($accountId=$!{session.getAttribute('front.userId')})</label> </td> <td class="tab-content2"> <select style="width:128px;" name="buildingId" id="buildingId" οnchange="getBuildId();"> <option value="$!{wyOwnerInfoEntity.buildingId}">==请选择==</option> #foreach($entity in $!{t_wy.findBuilding("$accountId")}) <option value="$!{entity.buildingId}"#if($!{buildingId}=="$!{entity.buildingId}")selected#end>$!{entity.buildingName}</option> #end </select> </td> </tr> <tr> <td class="tab-content1"> <label><span class="red">*</span>类型</label> </td> <td class="tab-content2"> <select style="width:128px;" name="paymentId" id="paymentId" οnchange="getPaymentId();"> <option value="">全部类型</option> #foreach($!{paymentEntity} in $!{t_wy.findWyPaymentItemListByStatusType()}) <option value="$!{paymentEntity.paymentId}" #if($!{paymentId}==$!{paymentEntity.paymentId}) selected #end >$!{paymentEntity.name}</option> #end </select> </td> </tr> <tr> <td class="tab-content1"> <label><span class="red">*</span>选择模板</label> </td> <td class="tab-content2" id="address_real"> <input type="file" id="xlsFile" οnchange="upload(this)" name="file" style="width: 300px;"/> <input type="hidden" id="uploadDir" name="uploadDir"/> </td> </tr> </tbody> </table> <div class="blank"></div> <div class="tab_button"> <button type="submit" id="submitBtnsusu">上 传</button> <button type="button" οnclick="javascript:history.back()">取 消</button> </div> <div class="blank"></div> </form> </div> <div class="cl"></div> </div> <div class="cl"></div> </div>
--------------struts2 java代码
package com.自己的包名 import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts2.interceptor.ServletResponseAware; import com.crenjoy.common.struts2.xwork2.BaseAction; i /** * 说明:实现ServletResponseAware类主要是为了file对象服务。 物业缴费信息批量导入excel * */ public class WyPayRecordInfoXlsUploadAction extends BaseAction implements ServletResponseAware { private static final long serialVersionUID = 1L; private static Log logger = LogFactory .getLog(WyPayRecordInfoXlsUploadAction.class); /** ID */ private String buildingId; /** ID */ private String paymentId; /** 上传文件的file对象 */ private File file; /** 上传后生成的文件名,注意属性名有明明规则,是file,则为 fileFileName,且为String类型 */ private String fileFileName; /** 文件类型,注意属性名有明明规则,是file,则为 fileContentType,且为String类型 */ private String fileContentType; private HttpServletResponse response; /** 保存上传后的临时文件的目录 */ private String fileTempPathName; /** 文件上传目录,由上传控件回调赋值 */ private String uploadDir; /** 返回客户端的结果集对象 */ Map<String, Object> resultMap = new HashMap<String, Object>(); /*** * 页面跳转 * * @return */ public String uploadExcel() { return SUCCESS; } /** * 初始化file对象. * * @return */ public String impExcel() { // 把上传的临时文件copy到指定的目录. File targetFile; try { SysConfig sysConfig = ConfigManager.create();//这个类自己写吧。 String ext = FilenameUtils.getExtension(fileFileName).toLowerCase(); String filename = UUID.randomUUID().toString() + "." + ext; targetFile = new File(sysConfig.getSysTempFilePath() + File.separator + filename); //logger.info("系统临时文件路径:" + sysConfig.getSysTempFilePath()); org.apache.commons.io.FileUtils.copyFile(file, targetFile); fileTempPathName = "tmp/" + filename; } catch (Exception e) { e.printStackTrace(); return this.writeJsonError(e.getMessage()); } return this.writeJson(fileTempPathName); } /** * 执行保存excel模板文件的方法. * * @return */ public void saveExcelInfo() { // 获取文件对象. File targetFile; // File("tmp/53487e62-4a2f-4838-a477-2359c67525dd.xls"); // SysConfig sysConfig = ConfigManager.create(); //系统临时文件路径:/Users/mac/Documents/tmp String sysTempFilePath = sysConfig.getSysTempFilePath(); //tmp + 文件名称 //截取上传的文件目录. String fileRelaPath=""; String tmp = uploadDir.substring(0, 3); //截取页面中传的存放文件临时目录 if("tmp".equals(tmp)) { String replace = uploadDir.replace(tmp, ""); //重新组装文件路径字符串 fileRelaPath = sysTempFilePath + replace; } //最综上传的文件对象. targetFile = new File(fileRelaPath); try { WyFactory.getWyServiceTypeAndStoreBuildingRemote().heatingCost(buildingId,paymentId,targetFile); resultMap.put("success", true); resultMap.put("mssage", "导入成功."); } catch (Exception e) { e.printStackTrace(); resultMap.put("success", false); resultMap.put("mssage", "导入失败."); this.writeJson(resultMap); } this.writeJson(resultMap); } public String getBuildingId() { return buildingId; } public void setBuildingId(String buildingId) { this.buildingId = buildingId; } public String getPaymentId() { return paymentId; } public void setPaymentId(String paymentId) { this.paymentId = paymentId; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public String getUploadDir() { return uploadDir; } public void setUploadDir(String uploadDir) { this.uploadDir = uploadDir; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } @Override public void setServletResponse(HttpServletResponse response) { this.response = response; } public String getFileTempPathName() { return fileTempPathName; } public void setFileTempPathName(String fileTempPathName) { this.fileTempPathName = fileTempPathName; } }