直接上代码:
jsp页面中:
<div style="margin: 20px;"> <span>当前最新固件 :</span><label style="margin-left: 10px; color: red;" id="currentFirmware"></label> </div> <div style="margin: 20px;"> <p><input type="file" name="firmware" id="firmware" /></p><!-- 注意name的写法 --> <p style="margin: 20px 0px 0px 15px;"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-upload'" onclick="doUpload();">上 传 固 件</a> (上传固件到服务器,并不更新网关)</p> <p style="margin: 20px 0px 0px 15px;"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-update'" onclick="updateGateway();">更 新 固 件</a> (把服务器上最新的固件远程更新到网关)</p> </div>
js:
var path = '<%=request.getContextPath()%>'; var sessionId = '<%=request.getSession().getId()%>';
$(function() { $('#firmware').uploadify( { 'buttonText' : '选 择 固 件', 'fileObjName' : 'firmware', // 需和input的name,以及struts2中的三个文件上传属性一致 'swf' : path + '/js/uploadify/uploadify.swf', 'uploader' : path + '/doUpload.action', // 必须全路径 uploadPorcessServlet 'multi' : false, 'auto' : false, 'fileTypeDesc' : '固件', 'fileTypeExts' : '*.bin', 'formData' : { 'sessionId' : sessionId },// sessionId用于解决session丢失的问题 'fileSizeLimit' : '10240KB', 'removeCompleted' : false, 'onUploadSuccess' : function(file, data, response) { //alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data); if (data != null && data != '' && data != 'null') { $.messager.alert('提示信息', data, 'info'); return; } else { $.messager.alert('提示信息', '上传成功', 'info'); //得到最新固件信息 getNewest(); } } }); //页面初始化时得到服务器上的最新固件 getNewest(); });
java类:
因为新的jdk已不支持通过sessionId得到session,所以要自己写个hashMap,保存session
package com.mhm.dto; import javax.servlet.http.HttpSession; import java.util.HashMap; public class LedSessionContext { private static LedSessionContext instance; private HashMap<String, HttpSession> sessionMap; private LedSessionContext() { sessionMap = new HashMap<String, HttpSession>(); } public static LedSessionContext getInstance() { if (instance == null) { instance = new LedSessionContext(); } return instance; } public synchronized void AddSession(HttpSession session) { if (session != null) { sessionMap.put(session.getId(), session); } } public synchronized void DelSession(HttpSession session) { if (session != null) { sessionMap.remove(session.getId()); } } public synchronized HttpSession getSession(String sessionId) { if (sessionId == null) return null; return (HttpSession) sessionMap.get(sessionId); } }
监听session的创建以及销毁
package com.mhm.listener; import java.util.HashMap; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.mhm.dto.LedSessionContext; public class SessionListener implements HttpSessionListener { public static HashMap<String, HttpSession> sessionMap = new HashMap<String, HttpSession>(); private LedSessionContext lsc = LedSessionContext.getInstance(); @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { lsc.AddSession(httpSessionEvent.getSession()); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { HttpSession session = httpSessionEvent.getSession(); lsc.DelSession(session); } }
Action:
// =========== 供上传使用的字段,必须和jsp页面一致============= private File firmware; private String firmwareFileName; private String firmwareFileContentType; // =========== 供上传使用的字段=============
@Action(value = "doUpload", results = { @Result(name = Constants.SUCCESS, type = "json") }) public String doUpload() { log.info("method begin: doUpload()"); PrintWriter out = null; try { HttpServletResponse response = getResponse(); response.setContentType("text/html;charset=UTF-8"); out = getResponse().getWriter(); String sessionId = (String)getRequest().getParameter("sessionId"); HttpSession session = LedSessionContext.getInstance().getSession(sessionId); Userinfo user = (Userinfo)session.getAttribute(LedConstants.LOGINUSER); if (user == null) { rtnMsg = "用户未登录或登录已超时。上传失败"; out.print(rtnMsg); out.flush(); out.close(); } else { String path = getRequest().getSession().getServletContext().getRealPath("/upload"); System.out.println("path : " + path); // 对文件类型过滤赞不考虑 if (firmware != null) { StringBuilder newFileName = new StringBuilder(); int dotPos = firmwareFileName.indexOf("."); String fName = firmwareFileName.substring(0, dotPos); newFileName.append(fName) .append("-") .append(UUID.randomUUID()) .append(firmwareFileName.substring(dotPos)); File savefile = new File(new File(path), newFileName.toString()); if (!savefile.getParentFile().exists()) { savefile.getParentFile().mkdirs(); } FileUtils.copyFile(firmware, savefile); // 上传信息存入数据库 Uploadfile entity = new Uploadfile(); entity.setFname(newFileName.toString()); entity.setOriginalName(firmwareFileName); entity.setFilePath(path + "\\" + newFileName.toString()); entity.setType(Constants.INT_VALUE1); entity.setFlag(Constants.INT_VALUE1); entity.setCreateDate(getNowTimestamp()); entity.setCreateUser(user.getUserId()); uploadFileMng.save(entity); out.print(""); out.flush(); out.close(); } } } catch (IOException ex) { log.error("doUpload()", ex); rtnMsg = ex.getLocalizedMessage(); out.print(rtnMsg); out.flush(); out.close(); } log.info("method begin: doUpload()"); return SUCCESS; }