一直以为ajax不能做上传,直到最近看了一些文章。需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T
代码和相关配置如下:
js代码:
需要导入jquery星河ajaxfileupload.js,html代码:
struts2 配置:
uploadTemp
后端struts2 action代码:
// 上传文件所需属性 private String title; private File uploadFile; private String uploadFileContentType; private String SavePath; private String uploadFileFileName; Log log = LogFactory.getLog(this.getClass());public String doUploadAndInsert() throws Exception { PrintWriter out = null; MsgBean msg = new MsgBean(); try { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); out = response.getWriter(); if(getUploadFile().length()>2097152){ msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail"); msg.setMsgText(getUploadFileFileName()+"上传失败,文件太大。\r\n请不要上传超过2048KB的文件"); out.write(JSON.toJSONString(msg)); out.flush(); return null; } //后缀名限制 String suffixName = getUploadFileFileName().split("\\.")[1]; if(!"xls".equalsIgnoreCase(suffixName)){ msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail"); msg.setMsgText(getUploadFileFileName()+"上传失败,错误的文件格式!"); out.write(JSON.toJSONString(msg)); out.flush(); return null; } UUID uuid = UUID.randomUUID(); ServletContext servletContext = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT); String rootPath = servletContext.getRealPath("/"); File folder = new File(rootPath + "\\" + getSavePath()); if (!folder.exists()) { folder.mkdir(); } FileOutputStream fileOutputStream = new FileOutputStream(rootPath + "\\" + getSavePath() + "\\" + uuid+"_"+getUploadFileFileName()); FileInputStream fileInputStream = new FileInputStream(getUploadFile()); byte[] buffer = new byte[1024]; int len = 0; while ((len = fileInputStream.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, len); } fileInputStream.close(); log.info("上传文件接收成功,文件存放全路径为:" + rootPath + "/" + uuid+"_"+getUploadFileFileName()); } catch (Exception e){ msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail"); msg.setMsgText(getUploadFileFileName()+"上传失败,"+e.getMessage()); out.write(JSON.toJSONString(msg)); out.flush(); } finally{ out.close(); return null; } }