Java file upload download, mail transceiver Instance code _java

Source: Internet
Author: User
Tags auth mixed sessions uuid

File upload Download

Front desk:

1. Submission Method: Post

2. The form has the file to upload the form item: <input type= "File"/>

3. Specify the form type:

Default type: enctype= "application/x-www-form-urlencoded"
File Upload type: multipart/form-data

FileUpload

File upload function is more commonly used in the development, Apache also provides file upload components!
FileUpload components:

1. Download source

2. Introduction of JAR file in project

Commons-fileupload-1.2.1.jar "File Upload component Core jar package"
Commons-io-1.4.jar "encapsulates the relevant tool classes for file processing"

Use:

public class Uploadservlet extends HttpServlet {//upload directory, save uploaded resources public void doget (HttpServletRequest request, Httpse Rvletresponse response) throws Servletexception, IOException {/********* file Upload component: Processing file Upload ************/try {//1. File Upload Factory Fi
Leitemfactory factory = new Diskfileitemfactory (); 2.
Create File upload core tool class Servletfileupload upload = new Servletfileupload (factory);
First, set the maximum size allowed for a single file: 30M Upload.setfilesizemax (30*1024*1024);
Second, set the File upload form to allow the total size: 80M Upload.setsizemax (80*1024*1024);
Third, set the upload form file name code//equivalent: Request.setcharacterencoding ("UTF-8");
Upload.setheaderencoding ("UTF-8"); 3. Determine if the current form is a file upload form if (upload.ismultipartcontent) {//4. Convert the request data to a Fileitem object, and then use a collection package list<fileitem>
List = Upload.parserequest (request); Traversal: Get each uploaded data for (Fileitem item:list) {//Judge: Normal text data if (Item.isformfield ()) {//Normal text data String FieldName = Item.getfi Eldname (); Form element name String content = item.getstring (); The form element name, corresponding data//item.getstring ("UTF-8"); Specifies the encoding System.out.println (fielDname + "" + content);} Upload file (file stream)----> upload to upload directory else {//plain text data string fieldName = Item.getfieldname ();//form element name String name = ITEM.G Etname (); FileName String content = item.getstring (); The form element name, the corresponding data String type = Item.getcontenttype (); File type InputStream in = Item.getinputstream ();
Upload file Stream * * Four, file name duplicate * for different user readme.txt files, do not want to overwrite!
* Background processing: To add a unique tag to the user!
*//A. Randomly generate a unique tag String id = uuid.randomuuid (). toString ();
B. stitching name with filename = id + "#" + name;
Get upload Base path String path = Getservletcontext (). Getrealpath ("/upload");
Creates the target file, filename = new file (path,name);
Tool class, File upload item.write (files); Item.delete ();
Delete system-generated temporary files System.out.println (); }} else {System.out.println ("The current form is not a file upload form, processing failed!") ");
}
}
catch (Exception e) {e.printstacktrace ();}} Manual implementation process private void upload (HttpServletRequest request) throws IOException, unsupportedencodingexception {/* REQUEST.G Etparameter (""); Get/post request.getquerystring (); Gets the data submitted by get Request.getinputstream (); Get the number of post submissionsAccording to * */*********** manually get file Upload form data ************///1.
Gets the form data stream InputStream in = Request.getinputstream (); 2.
Convert stream InputStreamReader instream = new InputStreamReader (in, "UTF-8"); 3.
Buffered stream BufferedReader reader = new BufferedReader (instream);
Output data String str = NULL;
while (str = Reader.readline ())!= null) {System.out.println (str);}//Close Reader.close ();
Instream.close ();
In.close (); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {thi
S.doget (request, response); }
}

Case:

index.jsp

<body> 
<a href= "${pagecontext.request.contextpath}/upload.jsp" > File upload </a>
<a href= "${ PageContext.request.contextPath}/fileservlet?method=downlist "> File download </a> 
</body>

upload.jsp

<body> 
<form name= "frm_test" action= "${pagecontext.request.contextpath}/fileservlet?method=upload" Method= "POST" enctype= "Multipart/form-data" >
<%--<input type= "hidden" name= "method" value= "Upload" >--%>
user name: <input type= "text" name= "UserName" > <br/>
File: <input type= "file" Name= "File_ IMG "> <br/>
<input type=" Submit "value=" submitted ">
</form>
</body>

Fileservlet.java

/** * Process file upload and download * @author Jie.yuan */public class Fileservlet extends HttpServlet {public void doget (Httpservletreque St request, httpservletresponse Response) throws Servletexception, IOException {//GET request parameters: distinguish between different operation types String method = requ
Est.getparameter ("method"); if ("Upload". Equals (method)) {//upload upload (request,response);} else if ("Downlist". Equals (method)) {//Enter the download list downlist (
Request,response);
else if (' Down '. Equals (method)) {//Download down (request,response);}} /** * 1. Upload/private void upload (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {try {//1. Create Factory object Fileitemfactory factory = new Diskfileitemfactory ();//2. File Upload core tool class Servletfileupload upload = new S
Ervletfileupload (Factory); Set the size limit parameter Upload.setfilesizemax (10*1024*1024); Single File size limit Upload.setsizemax (50*1024*1024); Total file size limit upload.setheaderencoding ("UTF-8"); The Chinese file encoding processing//judgment if (upload.ismultipartcontent (Request)) {//3. Convert request data to List collection List<fileitem> list = upload.parserequest (request);
Traversal for (Fileitem item:list) {//judgment: Normal text data if (Item.isformfield ()) {//get name String name = Item.getfieldname ();//Get value
String value = item.getstring ();
System.out.println (value); }//File table single else {/******** file upload ***********///A. Get the file name String name = Item.getname ();//----Handle the problem with duplicate filename name----//A1. First.
To a unique tag String id = uuid.randomuuid (). toString (); A2. 
Stitching filename name = id + "#" + name;
B. Get upload directory String basepath = Getservletcontext (). Getrealpath ("/upload");
C. Create the file object to upload files = new filename (basepath,name);
D. Upload item.write (file); Item.delete ();
Delete temporary files generated by component Runtime}} and catch (Exception e) {e.printstacktrace ();}} /** * 2. Go to download list * * private void Downlist (HttpServletRequest request, httpservletresponse response) throws Servletexception,
IOException {//implementation idea: First get the file name of all files in upload directory, then save; jump to down.jsp list to show//1. Initializes the Map collection map< contains a unique tag file name, short file name >;
map<string,string> fileNames = new hashmap<string,string> (); 2. Get the upload directory and all the files under itThe filename String bathpath = Getservletcontext (). Getrealpath ("/upload");
Directory File File = new file (Bathpath);
directory, all filename String list[] = File.list (); Traversal, encapsulating if (list!= null && list.length > 0) {for (int i=0; i<list.length; i++) {//full name String FileName = Li
St[i];
Short name String shortname = filename.substring (Filename.lastindexof ("#") +1);
Encapsulation Filenames.put (FileName, shortname); }//3.
Save to request Domain Request.setattribute ("fileNames", fileNames); 4.
Forwarding Request.getrequestdispatcher ("/downlist.jsp"). Forward (request, response); }/** * 3. Processing download/private void Down (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {///Get user downloaded file name (append data after URL address) String fileName = request.getparameter ("filename"); filename = new String (
Filename.getbytes ("Iso8859-1"), "UTF-8");
First get the upload directory path String basepath = Getservletcontext (). Getrealpath ("/upload");
Gets a file stream inputstream in = new FileInputStream (new file (Basepath,filename)); If the filename is in Chinese, URL encoding is required fiLename = Urlencoder.encode (FileName, "UTF-8");
Set Download response header Response.setheader ("Content-disposition", "attachment;filename=" + fileName);
Gets the response byte stream outputstream out = Response.getoutputstream ();
Byte[] B = new byte[1024];
int len =-1;
while (len = In.read (b))!=-1) {out.write (b, 0, Len);}//Close Out.close ();
In.close (); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {thi
S.doget (request, response); }
}

Mail development

Preparation work, environment setting:

1. Build a mail server locally

Easy mail server, Eyoumailserversetup.exe

2. New Mailbox Account

John send email to Dick.

Step 1:

New domain Name: tools, server settings, single domain name box input itcast.com

Step 2:

New Mailbox Account: Zhangsan@itcast.com

Lisi@itcast.com

3. Install Foxmail

Configure mail forwarding Server (SMTP): localhost 25
Mail receiving server (POP3): localhost 110

Then create a new account, you can receive mail!

Attention

Attention

If this is a Web project, there may be a problem because Java EE has a mail feature from it.

We want to use our own Mail.jar file features! Need to remove the Java EE Mail package!

Use:

JavaMail Development, first introduce JAR file:

Activation.jar "If you are using jdk1.6 or above, you can use this jar file" Mail.jar "mail to send the core package"/** * 1. Send a normal message * @author Jie.yuan * * */public class App_sendmail {@Test public void Testsend () throws Exception {//0. Message parameters Pro
Perties prop = new Properties (); Prop.put ("Mail.transport.protocol", "SMTP"); Specify protocol prop.put ("Mail.smtp.host", "localhost"); Host stmp.qq.com prop.put ("Mail.smtp.port", 25); Port Prop.put ("Mail.smtp.auth", "true"); User Password Authentication prop.put ("Mail.debug", "true"); Debug mode//1.
Create a conversation session sessions for a message = Session.getdefaultinstance (prop); 2.
Create a message body object (entire mail object) mimemessage message = new MimeMessage (session); 3.
Set the message body parameters://3.1 title Message.setsubject ("My first email");
3.2 Mail Delivery time message.setsentdate (new Date ());
3.3 Sender Message.setsender (new internetaddress ("zhangsan@itcast.com"));
3.4 Receiver Message.setrecipient (recipienttype.to, New internetaddress ("lisi@itcast.com")); 3.5 content Message.settext ("Hello, has been sent to success!") Text ... "); Simple plain Text mail message.savechanges (); Save the message (optional)//4. Send Transport trans = Session.gettranSport ();
Trans.connect ("Zhangsan", "888");
Send mail trans.sendmessage (message, message.getallrecipients ());
Trans.close (); }
}

with picture

/** * @author Jie.yuan * */public class App_2sendwithimg {//initialization parameters private static Properties prop;//Sender PR
Ivate static internetaddress Sendman = null; static {prop = new Properties (); Prop.put ("Mail.transport.protocol", "SMTP");//Specify Protocol Prop.put ("Mail.smtp.host", "Localh OST "); Host stmp.qq.com prop.put ("Mail.smtp.port", 25); Port Prop.put ("Mail.smtp.auth", "true"); User Password Authentication prop.put ("Mail.debug", "true"); Debug mode try {Sendman = new internetaddress ("zhangsan@itcast.com");} catch (Addressexception e) {throw new runtimeexcept
Ion (e);  @Test public void Testsend () throws Exception {//1. Create a message session sessions = Session.getdefaultinstance (prop);//2.
Create a Mail object mimemessage message = new MimeMessage (session); 3.
Set parameters: Title, sender, recipient, send time, Content Message.setsubject ("with picture Mail");
Message.setsender (Sendman);
Message.setrecipient (recipienttype.to, New internetaddress ("lisi@itcast.com"));
Message.setsentdate (New Date ()); /*************** Set message content: Multifunction user mail (related) *******************///4.1 Build a multi-function message block mimemultipart related = new Mimemultipart ("related");
4.2 Building Multi-function Message Block content = Left text + right picture resource mimebodypart content = new MimeBodyPart ();
MimeBodyPart resource = new MimeBodyPart ();
Set specific content: A. resources (picture) String FilePath = App_2SendWithImg.class.getResource ("8.jpg"). GetPath ();
DataSource ds = new Filedatasource (new File (FilePath));
DataHandler handler = new DataHandler (DS);
Resource.setdatahandler (handler); Resource.setcontentid ("8.jpg"); Set the resource name, give the foreign key reference//set the specific content: B. Text Content.setcontent (" good haha!")
"," Text/html;charset=utf-8 ");
Related.addbodypart (content);
Related.addbodypart (Resource);

/*******4.3 constructs complex messages quickly, adding them to the message ********/message.setcontent (related); 5.
Send Transport trans = Session.gettransport ();
Trans.connect ("Zhangsan", "888");
Trans.sendmessage (Message, message.getallrecipients ());
Trans.close (); }
}

picture + attachment

/** * 3. Message with picture resources and attachments * * @author Jie.yuan */public class App_3imgandatta {//initialization parameters private static Properties prop;//sender Privat
e static internetaddress Sendman = null; static {prop = new Properties (); Prop.put ("Mail.transport.protocol", "SMTP");//Specify Protocol Prop.put ("Mail.smtp.host", "Localh OST "); Host stmp.qq.com prop.put ("Mail.smtp.port", 25); Port Prop.put ("Mail.smtp.auth", "true"); User Password Authentication prop.put ("Mail.debug", "true"); Debug mode try {Sendman = new internetaddress ("zhangsan@itcast.com");} catch (Addressexception e) {throw new runtimeexcept
Ion (e);  @Test public void Testsend () throws Exception {//1. Create a message session sessions = Session.getdefaultinstance (prop);//2.
Create a Mail object mimemessage message = new MimeMessage (session); 3.
Set parameters: Title, sender, recipient, send time, Content Message.setsubject ("with picture Mail");
Message.setsender (Sendman);
Message.setrecipient (recipienttype.to, New internetaddress ("lisi@itcast.com"));
Message.setsentdate (New Date ()); * * with attachment (picture) mail Development//Build a total message block mimemultipart mixed = NEW Mimemultipart ("mixed");
---> Total mail quickly, set to Message.setcontent in the Mail object (mixed);
Left: (text + picture resources) MimeBodyPart (= new MimeBodyPart);
Right: Attachment MimeBodyPart right-hand = new MimeBodyPart ();
Set to total message Block Mixed.addbodypart (left);
Mixed.addbodypart (right);
/****** attachment ********/String Attr_path = This.getclass (). GetResource ("A.docx"). GetPath ();
DataSource Attr_ds = new Filedatasource (new File (Attr_path));
DataHandler Attr_handler = new DataHandler (ATTR_DS);
Right.setdatahandler (Attr_handler);
Right.setfilename ("A.docx"); /*************** Set message content: Multifunction user mail (related) *******************///4.1 Building a multi-purpose message block mimemultipart related = new
Mimemultipart ("related");
----> Set to the total mail fast left left.setcontent (related);
4.2 Building Multi-function Message Block content = Left text + right picture resource mimebodypart content = new MimeBodyPart ();
MimeBodyPart resource = new MimeBodyPart ();
Set specific content: A. resources (picture) String FilePath = App_3ImgAndAtta.class.getResource ("8.jpg"). GetPath ();
DataSource ds = new Filedatasource (new File (FilePath)); DataHandler handler = new DatahaNdler (DS);
Resource.setdatahandler (handler); Resource.setcontentid ("8.jpg"); Set the resource name, give the foreign key reference//set the specific content: B. Text Content.setcontent (" good haha!")
"," Text/html;charset=utf-8 ");
Related.addbodypart (content);
Related.addbodypart (Resource); 5.
Send Transport trans = Session.gettransport ();
Trans.connect ("Zhangsan", "888");
Trans.sendmessage (Message, message.getallrecipients ());
Trans.close (); }
}

The above is a small set to the introduction of the Java file upload download, mail send and receive instance code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.