package org.servlet; import java.io.*; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.entity.MailModel; import org.mail.SendMail; /** * 接收表单,处理附件,组装邮件对象,并调用发送接口 * @说明 在C盘创建临时文件 * @author fei.teng * @version 1.0 * @since */ @SuppressWarnings("serial") public class SendMailServlet extends HttpServlet { @SuppressWarnings( { "unchecked", "deprecation" }) @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 建立磁盘工厂 FileItemFactory factory = new DiskFileItemFactory(); // 表单域 ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; String bgimg = "1"; // 默认是第一个背景图片 try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } MailModel mail = new MailModel(); InputStream is = null; for (FileItem item : items) { if (!item.isFormField()) { // 如果是附件 if (item.getSize() > 0) { is = item.getInputStream(); String filename = ""; if (item.getName().indexOf("\\") == -1) { filename = "c:\\tmp\\" + item.getName(); } else { filename = "c:\\tmp\\" + item.getName().substring(item.getName().lastIndexOf("\\")); } if (is.markSupported()) { System.out.println("没有上传文件或文件已经删除"); } else { File file = new File(filename); FileOutputStream fos = new FileOutputStream(file); // 建立输出流 byte[] buffer = new byte[8192]; // 每次读8K字节,大文件上传没有问题 int count = 0; while ((count = is.read(buffer)) > 0) { // 循环写入到硬盘 fos.write(buffer, 0, count); } fos.close(); // 关闭输入输出流 is.close(); if (item.getFieldName().equals("ufile")) { mail.setFilePath(filename); } else if (item.getFieldName().equals("umusic")) { mail.setMusicPath(filename); } } } } else { // 处理文本信息 if (item.getFieldName().equals("title")) { mail.setTitle(item.getString("UTF-8")); } else if (item.getFieldName().equals("content")) { mail.setContext(item.getString("UTF-8")); } else if (item.getFieldName().equals("to")) { mail.setTo(item.getString("UTF-8")); } else if (item.getFieldName().equals("copy")) { mail.setCopy(item.getString("UTF-8")); } else if (item.getFieldName().equals("bgimg")) { bgimg = item.getString("UTF-8"); } } } String bgPath = request.getRealPath("/") + "\\images\\bg" + bgimg + ".jpg"; mail.setBgPath(bgPath); try { SendMail.sendMail(mail); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/sendmail.jsp"); } }
最近下载更多