Web day22 file Upload, download, JavaMail

Source: Internet
Author: User
Tags base64 save file

Upload

(Upload cannot use baseservlet)

1. Upload to form restrictions

*method= "POST"

*enctype= "Multipart/form-data"

* You need to add a file form item to the form: <inputtype= "file" name= "xxx"/>

<form action= "xxx" method= "post" enctype= "Multipart/form-data" >

User name; <input type= "text" name= "username"/><br/>

Photo: <input type= "file" Name= "Zhaopian"/><br/>

<input type= "Submit" value= "Upload"/>

</form>

2. Upload to servlet restrictions

*request.getparametere ("xxx"); This method is void when the form is Enctype= "Multipart/form-data". It will always return null

*servletinputstream Request.getinputstream (); the body containing the entire request!

-------------------------------

The body of a multi-part form

1. Every part is separated, that is, one form item.

2. A part contains the request header and the blank line, as well as the request body.

3. Normal form items:

> 1 headers: content-disposition: Contains name= "XXXX", which is the name of the form item.

The > body is the value of the table item

4. File Form items:

> 2 heads:

*content-disposition: Contains name= "XXXX", that is, the form item name, and a filename= "XXX", which indicates the name of the uploaded file

*content-type: It is the MIME type of the uploaded file, for example: Image/pjpeg, which is the picture that uploads the picture, the jpg extension on the image.

> is the content of uploading files.

===========================================

Commons-fileupload

*commons-fileupload.jar

*commons-io.jar

This widget will help us to parse the upload data in the request, and the result of parsing is that a single form item data is encapsulated into a Fileitem object. We just need to call the Fileitem Method!

---------------


1. Upload three steps

Related classes:

* Factory: Diskfileitemfactory

* Parser: Servletfileupload

* Form Item: Fileitem

1). Create Factory: Diskfileitemfactoryfactory = new Diskfileitemfactory ();

2). Create parser: Servletfileuploadsfu = new Servletfileupload (factory);

3). Use parser to parse request, get Fileitem set:list<fileitem> fileitemlist= sfu.parserequest (Request);


2. Fileitem

*boolean Isformfield (): Is a normal form item! Returns true for normal form items if False is the file form item!

*string getfieldname (): Returns the name of the current form item;

*string getString (String CharSet): Returns the value of the table item;

*string getName (): Returns the uploaded file name

*long getsize (): Returns the number of bytes uploaded to the file

*inputstream getInputStream (): Returns the input stream corresponding to the uploaded file

*void Write (file destfile): Saves the contents of the uploaded files to the specified file.

*string getContentType ();


Code

public class Upload2servlet extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {request.setcharacterencoding ("Utf-8"); Response.setcontenttype (" Text/html;charset=utf-8 ");/* * Upload three steps * 1. Get Factory * 2. Create a parser from the factory * 3. Parse request, get Fileitem set * 4. Traversing the Fileitem collection, calling its API to complete the file save */diskfileitemfactory Factory = new Diskfileitemfactory (); Servletfileupload SFU = new Servletfileupload (factory); try {list<fileitem> fileitemlist = sfu.parserequest ( request); Fileitem fi1 = fileitemlist.get (0); Fileitem Fi2 = fileitemlist.get (1); System.out.println ("Normal form Item Demo:" + fi1.getfieldname () + "=" + fi1.getstring ("UTF-8")); System.out.println ("File Form individual demo:"); System.out.println ("Content-type:" + fi2.getcontenttype ()); SYSTEM.OUT.PRINTLN ("Size:" + fi2.getsize ()); SYSTEM.OUT.PRINTLN ("FileName:" + fi2.getname ());//save File DestFile = new ("C:/baibing.jpg"); Fi2.write (DestFile) ;} catch (Fileuploadexception e) {throw new RuntimeException (e);}catch (Exception e) {throw new RuntimeException (e);}}} 


---------------


Details of the upload:

1. The file must be saved to Web-inf!

* Purpose is to not allow direct access to the browser!

* Save the file to the Web-inf directory!

2. File name related issues

* Some browsers upload filename is absolute path, this need to cut! C:\files\baibing.jpg

String filename = Fi2.getname ();

Intindex = filename.lastindexof ("\ \");

if (index!=-1) {

filename = filename.substring (index+1);

}

* File name garbled or normal table item garbled: request.setcharacterencoding ("Utf-8"), because FileUpload inside will call Request.getcharacterencoding ();

>request.setcharacterencoding ("Utf-8");//Low priority

>servletfileupload.setheaderencoding ("Utf-8");//High priority

* File name problem; We need to add a prefix to each file, which is guaranteed to not be duplicated. Uuid

>filename = Commonutils.uuid () + "_" + filename;

3. Catalog Break-up

* Multiple files cannot be stored in one directory.

> First character break: Use the first letter of the file as the directory name, for example: Abc.txt, then we save the file to a directory. If the A directory does not exist at this time, then create it.

> Time Break: Use the current date as a table of contents.

> Hash Break:

* Get int value by file name, call Hashcode ()

* it converts int value to 16 binary 0~9, a~f

* Get the top two bits of the 16 binary used to generate the directory, the directory is two levels! For example: 1b2c3d4e5f,/1/b/Save the file.

4. Size limit for uploaded files

* Single File size limit

> Sfu.setfilesizemax (100*1024): Limit single file size to 100KB

> The above method call must be called before parsing begins!

> If the uploaded file exceeds the limit, an exception will be thrown when the Parserequest () method executes! Fileuploadbase.filesizelimitexceededexception

* Entire request all data size limit

> Sfu.setsizemax (1024 * 1024);//Limit the entire form size to 1M

> This method must also be called before the Parserequest () method

> If the uploaded file exceeds the limit, an exception will be thrown when the Parserequest () method executes! Fileuploadbase.sizelimitexceededexception

5. Cache size and Temp directory

* Cache Size: How big it is before you save it to your hard drive! Default is 10KB

* Temp directory: What directory is saved to the hard disk

Set cache size with temp directory: Newdiskfileitemfactory (20*1024, New File ("F:/temp"))

Code

public class Upload3servlet extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {request.setcharacterencoding ("Utf-8"); Response.setcontenttype (" Text/html;charset=utf-8 ")/* * Upload three steps *///factory diskfileitemfactory factory = new Diskfileitemfactory (20*1024, New File (" f:/f /temp "));//parser servletfileupload SFU = new Servletfileupload (factory);//sfu.setfilesizemax (100 * 1024);// Limit the single file size to 100k//sfu.setsizemax (1024 * 1024);//Limit the entire form size to 1m//resolution, get listtry {list<fileitem> List = sfu.parserequest (request); Fileitem fi = list.get (1);///////////////////////////////////////////////////////* * 1. Get the file save path */string root = This.getservletcontext (). Getrealpath ("/web-inf/files/");/* * 2. Build two-level directory * 1). Get the file name * 2). Get Hashcode * 3). Forward to 16 in * 4). Gets the first two characters used to generate the directory */string filename = fi.getname ();//Gets the uploaded file name/* * handles the absolute path problem of the file name */int index = filename.lastindexof ("\ \"); if ( Index! =-1) {filename = filename.substring (index+1);} /* *Adds a UUID prefix to the file name, handles the file with the same name problem */string savename = commonutils.uuid () + "_" + filename;/* * 1. Get hashcode */int Hcode = Filename.hashcode (); String hex = integer.tohexstring (Hcode);/* * 2. Get the first two letters of hex, connect with root, generate a complete path */file dirfile = new File (root, Hex.charat (0) + "/" + Hex.charat (1));/* * 3. Create a directory chain */dirfile.mkdirs ();/* * 4. Create catalog file */file destfile = new File (Dirfile, savename);/* * 5. Save */fi.write (DestFile);///////////////////////////////////////////////////////} catch (Fileuploadexception e) {if ( e instanceof fileuploadbase.filesizelimitexceededexception) {Request.setattribute ("msg", "The file you uploaded exceeds the 100kb! "); Request.getrequestdispatcher ("/form3.jsp "). Forward (request, response);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


------------------------------



Download

1. Download is to respond to the client byte data!

It turns out that we're all responding to HTML character data!

Turn a file into a byte array, use Response.getoutputstream () to each browser!!!

2. Requirements for download

* Two heads a stream!

> Content-type: What MIME type is the file you pass to the client, for example: Image/pjpeg

* Call ServletContext's GetMimeType () method by file name to get MIME type!

> content-disposition: Its default value is inline, which means it opens in a browser window! Attachment;filename=xxx

* Following filename= is the name of the file that appears in the Download box!

> Stream: The file data to download!

* Own new one input stream can!

---------------------------

Download the details

1. When the Chinese name is displayed in the download box, garbled characters will appear.

*FIREFOX:BASE64 encoding.

* Most other browsers: URL encoding.

Generic scenario: filename = newstring (filename.getbytes ("GBK"), "iso-8859-1");


or ↓

Code

public class Download1servlet extends HttpServlet {@Overridepublic void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {/* * Two Header one stream * 1. Content-type * 2. Content-disposition * 3. Stream: Download file data */string filename = "f:/streamer fly. mp3";//To make the download box display Chinese file name is not garbled! String framename = new string ("Streamer% fluttering. mp3". GetBytes ("GBK"), "iso-8859-1"); String framename = filenameencoding ("Streamer% fluttering. mp3", req); String contentType = This.getservletcontext (). GetMimeType (filename);//Get MIME type by file name string contentdisposition = " Attachment;filename= "+ framename;//a stream fileinputstream input = new FileInputStream (filename);//Set Header Resp.setheader (" Content-type ", ContentType); Resp.setheader (" Content-disposition ", contentdisposition);// Gets the stream that is bound to the response end servletoutputstream output = Resp.getoutputstream (), ioutils.copy (input, Output),//writes data from the input stream to the output stream. Input.close ();} Used to encode the downloaded file name! public static string filenameencoding (string filename, httpservletrequest request) throws IOException {string agent = ReQuest.getheader ("User-agent"); Get the browser if (Agent.contains ("Firefox")) {Base64encoder Base64encoder = new Base64encoder (); filename = "=?utf-8?" B? " + Base64encoder.encode (filename.getbytes ("utf-8") + "? =";} else if (Agent.contains ("MSIE")) {filename = Urlencoder.encode (filename, "Utf-8");} else {filename = Urlencoder.encode ( FileName, "Utf-8");} return filename;}}



---------------------------

Java Mail


1 Sending and receiving mail

E-mail is sent from the client to the mail server, receiving mail is to download mail server mail to the client.

2 Overview of mail protocols

As with the HTTP protocol, a transport protocol is required to send and receive mail.

SMTP: E-mail protocol (Simple Mail Transfer Protocol, basic email Transfer Protocol);

POP3: (Post Office Protocol version 3, Post Office Agreement 3rd edition) receive email agreement;

IMAP: (Internet Message Access Protocol, Internet Messaging Access Protocol) send and receive mail protocol.

3 Sending and receiving mail procedures

Figure

4 Mail server name

The SMTP server has a port number of 25 and the server name is smtp.xxx.xxx.

The port number of the POP3 server is 110 and the server name is pop3.xxx.xxx.

Cases:

163:smtp.163.com and pop3.163.com;

126:smtp.126.com and pop3.126.com;

Qq:smtp.qq.com and pop3.qq.com;

Sohu:smtp.sohu.com and pop3.sohu.com;

Sina:smtp.sina.com and pop3.sina.com.

Telnet to send and receive mail

BASE64 is a cryptographic algorithm, this encryption is reversible! Its purpose is to make the encrypted text invisible to the naked eye.

Code

public class Base64utils {public static string encode (string s) {return encode (s, "Utf-8");} public static string decode (string s) {return decode (s, "Utf-8");} public static string encode (string s, string charset) {try {byte[] bytes = S.getbytes (charset); bytes = Base64.encodebase64 (bytes); return new String (bytes, charset);} catch (Exception e) {throw new RuntimeException (e);}} public static string decode (string s, string charset) {try {byte[] bytes = S.getbytes (charset); bytes = Base64.decodebase64 (bytes); return new String (bytes, charset);} catch (Exception e) {throw new RuntimeException (e);}}

JavaMail

Java Mail is a mail-specific API provided by Sun, the main jar package: Mail.jar, Activation.jar.

Main classes in Java Mail:

Javax.mail.Session: Session (equivalent to the Connection object when connecting to the database)

Javax.mail.internet.MimeMessage: Message class, contains the subject (title) of the message, content, recipient/Sender address, set cc/BCC, set attachments

Javax.mail.Transport: Used to send mail. It's a transmitter.

Code

public class Demo1 {@Testpublic void Fun1 () throws Exception {/* * 1. Get session */properties props = new Properties ();p ROP S.setproperty ("Mail.host", "smtp.163.com");p rops.setproperty ("Mail.smtp.auth", "true"); Authenticator auth = new Authenticator () {@Overrideprotected passwordauthentication getpasswordauthentication () { return new Passwordauthentication ("Itcast_cxf", "Itcast");}; Session session = Session.getinstance (props, auth);/* * 2. Create MimeMessage */mimemessage msg = new MimeMessage (session); Msg.setfrom (New InternetAddress ("[email protected]") );//Set Sender msg.setrecipients (recipienttype.to, "[email protected]");//Set Recipient msg.setrecipients ( recipienttype.cc, "[email protected]");//Set CC Msg.setrecipients (RECIPIENTTYPE.BCC, "[email protected]") ;//Set Dark send Msg.setsubject ("This is a test message from Itcast"); Msg.setcontent ("This is a spam message!"). "," Text/html;charset=utf-8 ");/* * 3. Hair */transport.send (msg);} /** * e-mail with attachments!!! */@Testpublic void fun2 () throws Exception {/* * 1. Get session */properties props = newProperties ();p rops.setproperty ("Mail.host", "smtp.163.com");p rops.setproperty ("Mail.smtp.auth", "true"); Authenticator auth = new Authenticator () {@Overrideprotected passwordauthentication getpasswordauthentication () { return new Passwordauthentication ("Itcast_cxf", "Itcast");}; Session session = Session.getinstance (props, auth);/* * 2. Create MimeMessage */mimemessage msg = new MimeMessage (session); Msg.setfrom (New InternetAddress ("[email protected]") );//Set Sender msg.setrecipients (recipienttype.to, "[email protected]");//Set recipient Msg.setsubject (" This is a test message from Itcast with an attachment ");/////////////////////////////////////////////////////////* * When sending a message containing an attachment, the message body is a multi-part form! * 1. Create a multipart part content! Mimemultipart * Mimemultipart is a collection that is used to load multiple body parts! * 2. We need to create two body parts, one for text content and the other for attachments. * Main part is called MimeBodyPart * 3. Set the Mimemultipart to mimemessage content! */mimemultipart list = new Mimemultipart ();//create multipart content//create Mimebodypartmimebodypart part1 = new MimeBodyPart ();// Set the content of the body part part1.setcontent ("This is a spam message containing attachments", "text/html;charset=utf-8");/Add the main part to the collection List.addbodypart (part1);//create Mimebodypartmimebodypart part2 = new MimeBodyPart ();p Art2.attachfile (new File ("f:/f/bai Bing. jpg"));//Set the contents of the Attachment Part2.setfilename (Mimeutility.encodetext ("BBW. jpg"));//Set the name of the display, Which Encodetext used to deal with Chinese garbled problem List.addbodypart (part2); msg.setcontent (list);//Set it to the message as the content of the message. * * 3. Hair */transport.send (msg);} @Testpublic void Fun3 () throws Exception {/* * 1. Get session */session session = Mailutils.createsession ("smtp.163.com", "I Tcast_cxf "," itcast ");/* * 2. Create mail object */mail mail = new Mail ("[email protected]", "[email protected],[email protected]", "Not junk e-mail What can it be?" "," Here is the text ");/* Create two Attachment objects */attachbean AB1 = new Attachbean (New File (" f:/f/bai Bing. jpg ")," Little Belle. jpg "); Attachbean ab2 = new Attachbean (New File ("F:/f/big.jpg"), "my Down jacket. jpg");//Added to Mail Mail.addattach (AB1); Mail.addattach ( AB2);/* * 3. Send */mailutils.send (session, mail);}}


Web day22 file Upload, download, JavaMail

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.