Example of jspsmart file upload and email sending

Source: Internet
Author: User

1. jspsmart File Upload (common form with common form fields and several file selection fields)

Page:
Copy codeThe Code is as follows:
<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>

<! -- Hide the file domain 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> -->
<! -- Hide the object domain 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 class:
Copy codeThe Code is as follows:
/**
* 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 the dataId directory
String newPath = estPath + "/" + dataId;
CreateDir (newPath );
// Generate the data directory
NewPath = estPath + "/" + dataId + "/data ";
CreateDir (newPath );
// Generate the 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 the temporary file corresponding to the item
}
} 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 sending:
Copy codeThe Code is as follows:
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 an attachment
Public static void addAttachemnt (String fPath ){
Vfile. add (fPath );
}
// Send an email
Public static void sendMail (String emailTo, String msg ){
// Vfile attachment file set
Try {
Properties props = new Properties (); // obtain the system environment
Authenticator auth = new EmailAuthenticator (username, password); // Authenticator
Props. put ("mail. smtp. host", host );
Props. put ("mail. smtp. auth", "true ");

Session session = Session. getDefaultInstance (props, auth );
// Set the session to communicate with the email server
MimeMessage message = new MimeMessage (session );
// Set the sender's address
Message. setFrom (new InternetAddress (username ));
// Set the email Receiving address
Message. addRecipient (Message. RecipientType. TO, new InternetAddress (emailTo ));
// Set the Email Subject
Message. setSubject (mailSubject );
// Construct Multipart
Multipart mp = new MimeMultipart ();
// Add the body to Multipart
MimeBodyPart content = new MimeBodyPart ();
Content. setContent (msg, "text/html; charset = gb2312 ");
Mp. addBodyPart (content );
// Add an attachment to 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 );
// Set the mail sending period
Message. setSentDate (new Date ());
Message. saveChanges ();
// Send an email
Transport. send (message );
} Catch (Exception e ){
E. printStackTrace ();
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.