jspsmart file upload with mail sent to the instance

  • 2020-05-27 06:53:30
  • OfStack

1. jspsmart file upload (common form, with common form field and several file selection fields)

Page:


<form class="form-horizontal" id= " estForm "  action="/tools/toolServlet?type=est" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Email" onblur="checkEmail()">
<span class="help-inline"></span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="file">File</label>
<div class="controls">
<input type="file" name="file" id="file" onchange="getFileInfo()"/>
<span class="help-inline"></span>
</div>
</div>
<!--  Hidden file field  begin
<div class="control-group" id="hiddenFileDiv" style="display: none;">
<label class="control-label" for="file">File</label>
<div class="controls">
<input type="file" name="file1" id="file1" />
<span class="help-inline"></span>
</div>
</div>-->
<!--  Hidden file field  end
<div class="control-group">
<label class="control-label" for="file">crossmatch</label>
<div class="controls">
<select name="crossmatch" id="crossmatch">
<option value="Y">Y</option>
<option value="N">N</option>
</select>
<span class="help-inline"></span>
</div>
</div>-->
<div class="control-group">
<div class="controls">
<!-- <a href="javascript:void(0);" id="upload" class="btn">submit</a>-->
<button type="submit" class="btn" id="upload">submit</button>
<button type="reset" class="btn" id="reset">reset</button>
</div>
</div>
</form>

Processing categories:

/**
*  File upload 
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doUpload(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
boolean flag = true;
String email = "";
String dataId = String.valueOf(new Date().getTime());
// generate dataId directory 
String newPath = estPath + "/" + dataId;
createDir(newPath);
// generate data directory 
newPath = estPath + "/" + dataId + "/data";
createDir(newPath);
// generate data directory 
newPath = estPath + "/" + dataId + "/result";
createDir(newPath);
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List<FileItem> list = upload.parseRequest(req);
for(FileItem item : list){
if(!(item.isFormField())){
System.err.println("item name:" + item.getName());
if((item!=null)&&(item.getName()!=null)&&(!(item.getName().equals("")))){
String uploadFilename = item.getName();
// Process file upload 
InputStream in = item.getInputStream();
int len = 0;
byte[] b = new byte[1024];
newPath = estPath + "/" + dataId + "/data/";
FileOutputStream out = new FileOutputStream(newPath + uploadFilename);
while((len=in.read(b))>0){
out.write(b, 0, len);
}
in.close();
out.close();
item.delete(); // delete item The corresponding temporary file 
}
}else{
String fValue = item.getString();
if(fValue.indexOf("@")!=-1){
// email 
email = fValue;
System.err.println("email:" + email);
}
}
}
}catch (Exception e) {
flag = false;
System.err.println(" File upload failed! " + e);
}
}
req.setAttribute("flag", flag);
req.getRequestDispatcher("/view/est.jsp").forward(req, resp);
}

2. Email:

public class EmailAttachService {
private static String host = "smtp.163.com";
private static String username = "";
private static String password = "";
private static String mailSubject = "";
public static Vector vfile = new Vector();
// Add attachments 
public static void addAttachemnt(String fPath){
vfile.add(fPath);
}
// Send E-mail 
public static void sendMail(String emailTo,String msg) {
// vfile  Attachment file collection 
try {
Properties props = new Properties();//  Get the system environment 
Authenticator auth = new EmailAuthenticator(username, password);//  Conduct mail service user authentication 
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, auth);
//  Set up the session, Communicate with the mail server 
MimeMessage message = new MimeMessage(session);
//  Set the email sender's address 
message.setFrom(new InternetAddress(username));
//  Set the address to receive mail 
message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
//  Set email subject 
message.setSubject(mailSubject);
//  structure Multipart
Multipart mp = new MimeMultipart();
//  to Multipart To add text 
MimeBodyPart content = new MimeBodyPart();
content.setContent(msg, "text/html;charset=gb2312");
mp.addBodyPart(content);
//  to Multipart Add attachments 
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);
//  Set the time for the message to be sent 
message.setSentDate(new Date());
message.saveChanges();
// Send E-mail 
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}


Related articles: