
JavaWeb实现文件上传及邮件发送
发布日期:2021-05-09 09:24:32
浏览次数:17
分类:博客文章
本文共 18307 字,大约阅读时间需要 61 分钟。
目录
文件上传
pom.xml配置,导入文件上传的相应jar包
javax.servlet.jsp javax.servlet.jsp-api 2.3.3 javax.servlet servlet-api 2.5 commons-io commons-io 2.6 commons-fileupload commons-fileupload 1.3.3
index.jsp,设置表单enctype="multipart/form-data"
<%@page contentType="text/html;charset=UTF-8" language="java" %>
文件上传具体实现Servlet
public class FileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost..."); //判断是普通的表单还是带文件的表单 if (!ServletFileUpload.isMultipartContent(req)) { System.out.println("return"); return;//终止方法运行 } System.out.println("path"); //创建上传文件的保存路径,保存在WEB-INF下,用户无法直接访问 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadfile = new File(uploadPath); if (!uploadfile.exists()) { uploadfile.mkdir();//创建 } //缓存 临时文件 System.out.println("tempPath"); String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); System.out.println(tempPath); File tempFile = new File(tempPath); if (!tempFile.exists()) { tempFile.mkdir();//创建临时目录 } try { System.out.println("start"); //处理文件的上传路径和大小 DiskFileItemFactory factory = getDiskFileItemFactory(tempFile); //获取ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //处理上传的文件 String msg = uploadParseRequest(upload, req, uploadPath); req.setAttribute("msg",msg); req.getRequestDispatcher("info.jsp").forward(req,resp); } catch (FileUploadException e) { e.printStackTrace(); } } public static DiskFileItemFactory getDiskFileItemFactory(File file){ DiskFileItemFactory factory = new DiskFileItemFactory(); //设置缓冲区,上传文件大于缓冲区的时候,放入临时文件 factory.setSizeThreshold(1024*1024); factory.setRepository(file);//临时目录 System.out.println("factorty!!"); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){ ServletFileUpload upload = new ServletFileUpload(factory); //监听文件上传进度 upload.setProgressListener(new ProgressListener() { @Override public void update(long pByteRead, long pContentLength, int pItems) { System.out.println("总大小"+pContentLength+"已上传:"+pByteRead); } }); //处理乱码问题 upload.setHeaderEncoding("UTF-8"); //设置单个文件的最大值 upload.setFileSizeMax(1024*1024*10); //设置总共能够上传的文件的大小 upload.setSizeMax(1024*1024*10); return upload; } public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest req,String uploadPath) throws IOException, FileUploadException { String msg = ""; //处理上传文件 //把前端的请求封装成一个FileItems对象 ListfileItems = upload.parseRequest(req); for (FileItem fileItem : fileItems) { //判断是普通的表单还是带文件的表单 if (fileItem.isFormField()){ //getFieldName是前端表单控件的name String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8"); System.out.println(name+":"+value); }else { //处理上传的文件 String uploadFileName = fileItem.getName(); System.out.println("上传的文件名是“"+uploadFileName); if (uploadFileName.trim().equals("")||uploadFileName==null){ continue; } //获得上传文件名 String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); //获得文件的后缀名 String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf("." )+1); System.out.println(fileName+"文件"+fileExtName); //生成唯一识别的通用码 String uuidPath = UUID.randomUUID().toString(); String realPath = uploadPath+"/"+uuidPath; File realPathFile = new File(realPath); if (!realPathFile.exists()){ realPathFile.mkdir(); } //存放的地址 //文件传输 InputStream inputStream = fileItem.getInputStream(); FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); byte[] buffer = new byte[1024*1024]; int len = 0; while ((len=inputStream.read(buffer))>0){ fos.write(buffer,0,len); } fos.close(); inputStream.close(); msg = "上传成功!"; fileItem.delete();//上传成功,删除临时文件 } } return msg; }}
web.xml
FileServlet com.zr.FileServlet FileServlet /upload.do
info.jsp上传成功界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>Title ${msg}
邮件发送
新建Java项目,在lib包中导入activation-1.1.1.jar和mail-1.4.7.jar,右击lib,点击add as library添加到项目依赖中。
以qq邮箱为例:设置中开启SMTP和POP3服务获取授权码,以下例子中qjpgitodfatwbbfg为我的qq邮箱授权码。
简单邮件(只有文字的)
package com.zr;import com.sun.mail.util.MailSSLSocketFactory;import java.security.GeneralSecurityException;import java.util.Properties;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class MailTest { //简单邮件 没有图片和附件 纯文字 //复杂邮件 有图片和附件 //发送邮件 需开启smtp pop3服务 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //设置qq邮件服务器 prop.setProperty("mail.transport.protocol","smtp"); //邮件发送协议 prop.setProperty("mail.smtp.auth","true"); //需要验证用户名和密码 //qq邮箱 需要设置SSL加密(其它邮箱不需要) MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //创建定义整个应用程序所需环境信息的Session对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //开启Session的Debug模式,看到程序发送Email运行状态 session.setDebug(true); //通过Session得到transport对象 Transport ts = session.getTransport(); //使用邮件的用户名和授权码连上邮件服务器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); //创建邮件 //创建邮件对象 MimeMessage message = new MimeMessage(session); //邮件的发件人 message.setFrom(new InternetAddress("813794474@qq.com")); //邮件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //邮件的标题 message.setSubject("简单邮件"); //邮件内容 message.setContent("你好啊!","text/html;charset=UTF-8"); //发送 ts.sendMessage(message,message.getAllRecipients()); ts.close(); }}
文字+图片邮件
package com.zr;import com.sun.mail.util.MailSSLSocketFactory;import java.security.GeneralSecurityException;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class MailTest2 { //简单邮件 没有图片和附件 纯文字 //复杂邮件 有图片和附件 //发送邮件 需开启smtp pop3服务 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //设置qq邮件服务器 prop.setProperty("mail.transport.protocol","smtp"); //邮件发送协议 prop.setProperty("mail.smtp.auth","true"); //需要验证用户名和密码 //qq邮箱 需要设置SSL加密(其它邮箱不需要) MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //创建定义整个应用程序所需环境信息的Session对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //开启Session的Debug模式,看到程序发送Email运行状态 session.setDebug(true); //通过Session得到transport对象 Transport ts = session.getTransport(); //使用邮件的用户名和授权码连上邮件服务器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); //创建邮件 //创建邮件对象 MimeMessage message = new MimeMessage(session); //邮件的发件人 message.setFrom(new InternetAddress("813794474@qq.com")); //邮件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //邮件的标题 message.setSubject("带图片的邮件"); //准备图片的数据 MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\404.jpg")); image.setDataHandler(dh); image.setContentID("404.jpg"); //准备正文数据 MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一个带图片的邮件","text/html;charset=UTF-8"); //描述数据关系 MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); //附件用mixed mm.setSubType("related"); //设置到消息中 保存修改 message.setContent(mm); message.saveChanges(); //发送 ts.sendMessage(message,message.getAllRecipients()); ts.close(); }}
文字+图片+附件邮件
package com.zr;import com.sun.mail.util.MailSSLSocketFactory;import java.security.GeneralSecurityException;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class MailTest3 { //简单邮件 没有图片和附件 纯文字 //复杂邮件 有图片和附件 //发送邮件 需开启smtp pop3服务 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //设置qq邮件服务器 prop.setProperty("mail.transport.protocol","smtp"); //邮件发送协议 prop.setProperty("mail.smtp.auth","true"); //需要验证用户名和密码 //qq邮箱 需要设置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //创建定义整个应用程序所需环境信息的Session对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //开启Session的Debug模式,看到程序发送Email运行状态 session.setDebug(true); //通过Session得到transport对象 Transport ts = session.getTransport(); //使用邮件的用户名和授权码连上邮件服务器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); MimeMessage mimeMessage = imageMail(session); //发送 ts.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); ts.close(); } public static MimeMessage imageMail(Session session) throws Exception{ //创建邮件 //创建邮件对象 MimeMessage message = new MimeMessage(session); //邮件的发件人 message.setFrom(new InternetAddress("813794474@qq.com")); //邮件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //邮件的标题 message.setSubject("带图片和附件的邮件"); //准备图片的数据 MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\404.jpg")); image.setDataHandler(dh); image.setContentID("404.jpg"); //准备正文数据 MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一个带图片的邮件","text/html;charset=UTF-8"); //附件 MimeBodyPart body3 = new MimeBodyPart(); body3.setDataHandler(new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\ext.txt"))); body3.setFileName("e.txt"); //描述数据关系 MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); //附件用mixed mm.setSubType("related"); //将图片和文本设置为主体 MimeBodyPart context = new MimeBodyPart(); context.setContent(mm); //拼接附件 MimeMultipart all = new MimeMultipart(); all.addBodyPart(body3); all.addBodyPart(context); all.setSubType("mixed"); //设置到消息中 保存修改 message.setContent(all); message.saveChanges(); return message; }}
注册成功邮件发送
新建Maven项目,在pom.xml中导入jsp,servlet,mail,activation相关的jar包依赖。
index.jsp 注册界面
info.jsp 注册后跳转的界面
***网站温馨提示
${message}
User 用户的pojo类
package com.zr.pojo;public class User { private String username; private String password; private String email; public User() { } public User(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; }}
邮件发送的工具类
package com.zr.util;import com.sun.mail.util.MailSSLSocketFactory;import com.zr.pojo.User;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;//多线程改善用户体验 异步public class SendMail extends Thread{ private String from = "813794474@qq.com"; private String username = "813794474@qq.com"; private String password = "qjpgitodfatwbbfg"; private String host = "smtp.qq.com"; private User user; public SendMail(User user){ this.user = user; } @Override public void run() { try { Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); //设置qq邮件服务器 prop.setProperty("mail.transport.protocol", "smtp"); //邮件发送协议 prop.setProperty("mail.smtp.auth", "true"); //需要验证用户名和密码 //qq邮箱 需要设置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); //创建定义整个应用程序所需环境信息的Session对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com", "qjpgitodfatwbbfg"); } }); //开启Session的Debug模式,看到程序发送Email运行状态 session.setDebug(true); //通过Session得到transport对象 Transport ts = session.getTransport(); //使用邮件的用户名和授权码连上邮件服务器 ts.connect(host, username, password); //创建邮件 //创建邮件对象 MimeMessage message = new MimeMessage(session); //邮件的发件人 message.setFrom(new InternetAddress(from)); //邮件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //邮件的标题 message.setSubject("注册邮件"); String info = "恭喜你注册成功!你的用户名:"+user.getUsername()+",密码:"+user.getPassword()+",请妥善保管!!"; //邮件内容 message.setContent(info, "text/html;charset=UTF-8"); message.saveChanges(); //发送 ts.sendMessage(message, message.getAllRecipients()); ts.close(); }catch (Exception e){ e.printStackTrace(); } }}
RegisterServlet编写
public class RegisterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收用户的请求 封装成对象 try { String username = req.getParameter("username"); String passeord = req.getParameter("passeord"); String email = req.getParameter("email"); User user = new User(username,passeord,email); //使用线程发送邮件,防止耗时,或注册人数过多引起的问题 SendMail sendMail = new SendMail(user); sendMail.start(); //sendMail.run(); //用户登录注册成功后 给用户发一封邮件 //使用线程来发送邮件 防止出现耗时,和网站注册人数过多的情况 req.setAttribute("message","注册成功!!邮件已经发送到你的邮箱!注意查收!"); req.getRequestDispatcher("info.jsp").forward(req,resp); } catch (Exception e) { e.printStackTrace(); req.setAttribute("message","注册失败!"); req.getRequestDispatcher("info.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月15日 00时20分14秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
ado读取多条oracle数据,Oracle ADO数据存取
2023-01-24
android fastjson漏洞_初识Fastjson漏洞(环境搭建及漏洞复现)
2023-01-24
android进程管理策略,Android进程保活
2023-01-24
arduino蓝牙通讯代码_arduino 联接蓝牙模块
2023-01-24
aspen串联反应怎么输入_如何进步提升串联谐振试验装置的稳定性
2023-01-24
aspose html转pdf_Java实现Word/Pdf/TXT转html
2023-01-24
a推b等价于非a或b_AB胶/蜜月胶常见问题的原因分析及解决方法
2023-01-24
bat 命令返回结果_【批处理】带你入门命令行
2023-01-24
c++ string取子串_Integer与String的设计哲学
2023-01-24
c++ 数组批量赋值_数组之间不能赋值?穿个马甲吧!
2023-01-24
cad模糊查询符号_mysql 正则模式和like模糊查询
2023-01-24
ctrl c 和 ctrl v 不能用了_神奇操作,原来CTRL键还能这么用
2023-01-24
cytoscape安装java_Cytoscape史上最全攻略
2023-01-24
c语言程序设计年历显示,C语言程序设计报告《万年历》.doc
2023-01-24
C语言程序设计梁海英答案,1.5 习题
2023-01-24
c语言编写单片机中断,C语言AVR单片机中断程序写法
2023-01-24