1、ajaxfileupload:ajax文件上传
页面:
//文件上传
function fileUpload(){ $.ajaxFileUpload({ url:"/tools/toolServlet?type=estUpload&email=" + email, secureuri:false, fileElementId:'file1',//注:file id须用单引号引起来 dataType: "json", success:function(responseText,state){ } }); }servlet:
private void estUploadFile(HttpServletRequest request,
HttpServletResponse response) { pDataId = ""; long dataId = new Date().getTime(); String email = request.getParameter("email"); response.setContentType("text/html; charset=UTF-8"); String basePath = estPath + "/" + dataId; //生成dataId目录 String newPath = estPath + "/" + dataId; createDir(newPath); //生成data目录 newPath = estPath + "/" + dataId + "/data"; createDir(newPath); //生成data目录 newPath = estPath + "/" + dataId + "/result"; createDir(newPath); //创建存放图片的目录 newPath = this.getServletContext().getRealPath("/upload/est/" + dataId); createDir(newPath); // 查输入请求是否为multipart表单数据 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(10240);// 设置文件上传用于临时存放文件的内存大小,多于的部分将临时存放在硬盘 factory.setRepository(new File(this.getServletContext() .getRealPath("/temp"))); ServletFileUpload upload = new ServletFileUpload(factory); //监听文件上传进度 upload.setProgressListener(new UploadProgressListener(request)); upload.setSizeMax(2560 * 1024 * 1024); // 保存表单中所有请求 表单域 List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { if (e instanceof SizeLimitExceededException) { e.printStackTrace(); return; } } if (items != null) { for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); System.out.println("表单域名为:" + name + "表单域值为:" + value); } else { // 获取文件名及路径 String fileName = item.getName(); if (fileName != null) { File fullFile = new File(fileName); if (!fullFile.exists()) { File fileOnServer = new File(basePath + "/data", fullFile.getName()); item.write(fileOnServer); } } } } pDataId = String.valueOf(dataId); return; } } catch (FileUploadException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } } else { System.out.println("the enctype must be multipart/form-data"); return; } }2、jqGrid:主要是学会了双击事件,和添加自定义html元素,如按钮等
//加载表格
function refreshTable(){ $("#accountGroupTable").jqGrid({ url:"account-group", datatype:'json', rownumbers:true, rownumWidth:30, colNames:['ID','remark','账户组名称','账户组描述','创建时间','操作'], colModel:[ {name:'accountGroupId',index:'accountGroupId',hidden:true,align:'left'}, {name:'remark',index:'remark',hidden:true,align:'left'}, {name:'accountGroupName',index:'account_group_name', width:100,align:'left'}, {name:'remark',index:'remark',align:'left', width:100,formatter:function(cellvalue,options,rowObject){ if(cellvalue.length>15){ return cellvalue.substring(0,15)+"…"; }else{ return cellvalue; } }}, {name:'createDate',index:'create_date', width:100,align:'left'}, {name:'action2',index:'action2',align:'center',width:50,sortable:false,formatter:function(cellvalue, options, rowObject){//添加html元素 var del="<button οnclick=\"delAccountGroup('"+options.rowId+"')\">删除</button>"; return del; }} ], ondblClickRow : function(rowid, iRow, iCol, e) {//双击事件 updateAccountGroup(rowid); }, prmNames:{ page:"page.currentPage", rows:"page.pageSize" }, rowList:[10,20,30,50], pager:'#pager', viewrecords:true, rowNum : 10, sortable:true, sortname:'account_group_name', //从后台初始加载数据时按照哪个字段排序 sortorder:'desc', jsonReader:{ root:'datas',//json 中代表实际模型数据的入口 cell:'', page:"page.currentPage",//json 中代表当前页码的数据 total:"page.totalPage",//json 中代表页码总数的数据 records:"page.rowCount",//json 中代表数据行总数的数据 repeatitems:false }, shrinkToFit:true,//表格分配 autoScroll: true, hidegrid:false, hiddengrid:false, autowidth:false, height:300, width:600, gridComplete: function(){ $(document).find("th:first").html("序号"); } });}3、linux命令:主要是学会了使用linux命令上传文件,以及关闭、重启tomcat
//上传文件使用scp,如:
scp tools.war root@10.192.22.119:/usr/local/apache-tomcat-6.0.29/webapps
//关闭、重启tomcat
ssh root@ip地址
/usr/local/apache-tomcat-6.0.29/bin/shutdown.sh
/usr/local/apache-tomcat-6.0.29/bin/startup.sh
4、文件上传带进度显示
public class UploadProgressListener implements ProgressListener {
private HttpServletRequest request; private DecimalFormat df = new DecimalFormat("#00.0"); public UploadProgressListener(HttpServletRequest request){ this.request = request; } @Override public void update(long bytesRead, long bytesTotal, int items) { double percent= (double)bytesRead*100/(double)bytesTotal; request.getSession().setAttribute("uploadPercent", df.format(percent)); }}
servlet:
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度 upload.setProgressListener(new UploadProgressListener(request));......
页面:
var setinterval = setInterval("getUploadMeter()",200);
//读取文件上传进度
function getUploadMeter(){ $.get("/tools/toolServlet?type=readUploadPercent","",function(data){ var dataArray = data.split(","); $("#file1").parent().parent().find(".help-inline").html("已上传" + dataArray[0] + "%"); //上传完成 if(dataArray[0]=="100"){ clearInterval(setinterval); } }); }servlet:
//读取文件上传进度
private void readUploadPercent(HttpServletRequest request, HttpServletResponse response){ HttpSession session = request.getSession(); Object upload_percentage = session.getAttribute("uploadPercent"); if(upload_percentage==null) return; if("0".equals(upload_percentage.toString())) return; PrintWriter out; try { int endIndex = upload_percentage.toString().indexOf("."); out = response.getWriter(); String percent = upload_percentage.toString().substring(0, endIndex); out.write(percent+","+pDataId); out.flush(); } catch (IOException e) { e.printStackTrace(); } }5、backToTop插件
6、发送带附件的EmailService:
public class EmailAttachService {
private static String host = "smtp.163.com"; private static String username = "*@163.com"; private static String password = "*****"; private static String mailSubject = ""; public static Vector vfile = new Vector(); //添加附件 public static void addAttachemnt(String fPath){ vfile.add(fPath); } //发送邮件 public static void sendMail(String emailTo,String msg) { // vfile 附件文件集合 try { Properties props = new Properties();// 获取系统环境 Authenticator auth = new EmailAuthenticator(username, password);// 进行邮件服务用户认证 props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true");Session session = Session.getDefaultInstance(props, auth);
// 设置session,和邮件服务器进行通讯 MimeMessage message = new MimeMessage(session); // 设置邮件发送者的地址 message.setFrom(new InternetAddress(username)); // 设置邮件接收的地址 message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); // 设置邮件主题 message.setSubject(mailSubject); // 构造Multipart Multipart mp = new MimeMultipart(); // 向Multipart添加正文 MimeBodyPart content = new MimeBodyPart(); content.setContent(msg, "text/html;charset=gb2312"); mp.addBodyPart(content); // 向Multipart添加附件 Enumeration efile = vfile.elements(); while(efile.hasMoreElements()){ MimeBodyPart fattach = new MimeBodyPart(); String fName = efile.nextElement().toString(); FileDataSource fds = new FileDataSource(fName); fattach.setDataHandler(new DataHandler(fds)); fattach.setFileName(MimeUtility.encodeWord(fds.getName(), "GB2312",null)); mp.addBodyPart(fattach); } vfile.removeAllElements(); message.setContent(mp); // 设置邮件发送时期 message.setSentDate(new Date()); message.saveChanges(); //发送邮件 Transport.send(message); } catch (Exception e) { e.printStackTrace(); } }