Javaweb file upload and download & Mail Technology (18)

Source: Internet
Author: User
Tags file upload progress bar temporary file storage uuid

Introduction to File Upload

Recently found that few write a brief introduction, saying that they do not have time to write, may be to persuade themselves. In short, can write more than write. There is a persistent problem, the quality of the blog written every day is not very good. Convince yourself again, now in the learning phase, blogging in order to consolidate the knowledge point, so that later review use. In fact, every time I write a blog before the notes have been written on the nopad++, so most of the WLW on the direct paste, please forgive me

1. Necessary prerequisites for File upload
1. Form form: Property enctype must have a value of Multipart/form-dataenctype default value is: Application/x-www-form-urlencodedform enctype property and request message Header " Content-type "function is the same, tell the server request body Type 2. Submit Request method: Post3. Upload input domain for <input type= "file" name= "F1"/>
2. Form Request Body Content
1. application/x-www-form-urlencoded: Request body: Name=abc&password=123&gender=female2. When the form's enctype= "Multipart/form-data" the body content:-----------------------------7de771e40c46         The delimiter is divided into three parts: Each part is a content-disposition:form-data that is described with a MIME protocol; Name= "Name" Goudan-----------------------------7de771e40c46content-disposition:form-data; Name= "F1"; Filename= "A.txt" Content-type:text/plainaaaaaaaaaaa-----------------------------7de771e40c46content-disposition : Form-data; Name= "F2"; Filename= "B.txt" content-type:text/plainbbbbbbbbbbbbbbbbbbb-----------------------------7de771e40c46--
3. How the file is uploaded
Parsing the request body is a multipart/form-data type of data
4. File upload with third-party components
Commons-fileupload commonly used classes: Diskfileitemfactory: The factory class that produces fileitem new diskfileitemfactory (int sizethreshold, File Repository) Sizethreshold: Specifies a cache size. Default size 10Kbrepository: The directory where the disk temporary files are stored. The default is the current user's system temp file directory New Diskfileitemfactory () Servletfileupload: Core parser Fileitem: Represents the transfer of a form onto a domain
File upload combined with case to expand knowledge 1. File upload and 9 attention issues and solutions
File Upload 1. Solve garbled problem, request set the code (can solve the problem of uploading file name garbled) 2. Gets the resource path to the saved file 3. Determine if the path exists, and if it does not exist, create 4. Determines whether the enctype of the form submission is MULTIPART/FORM-DATA5. Get the File Upload object 6. Convert the user's request to get a list<fileitem>7. Iterate over the collection to get each object 8. Determine if each object is a normal field, and if it is a normal field, get the field name and field value (you can specify encoding) 9. Gets the MIME type of the object 10 if it is not a normal field. Determines whether the type is an image type (restricts download of only the image type) 11. Gets the filename of the uploaded file 12. According to Hashcode to generate the absolute path of level two subdirectory to get the hashcode of the file, according to the bitwise operation and left to move the Mosaic subdirectory, determine whether the folder exists, return to the directory after stitching 13. Gets the output stream associated to the generated directory 14. Gets the input stream 15 through the traversed object. Ioutils tool Copy 16. After you close the stream, do not forget to delete the temporary file file upload 9 questions to consider 1, how to ensure the security of the server to save the file directory under the Web-inf 2, the Chinese encoding problem: A, ordinary field Chinese value fileitem.getstring ("UTF-8"); b, Chinese filename request.setcharacterencoding ("UTF-8"); 3, prevent too many files under one folder storage A, sub-date creation: Today's uploaded files are placed in a folder named after today's date B,  Use the hashcode of the file name to store the directory 4, prevent the same folder file duplicate ID store_path old_filename new_filename user_id1/web-inf/files/20140109a.txt UUID1.TXT1 2/web-inf/files/20140109a.txt uuid2.txt2 No database UUID1_A.TXTUUID2_A.TXT5, limit the size of uploaded files: A, Single File size Servletfileupload.setfilesizemax (2*1024*1024), B, total file size servletfileupload.setsizemax6, Temporary file problem: Commons-fileupload, upload using cache, default is 10kb, exceed 10kb upload file, use disk as temporary cache (temporary file, where exists?). The default is the system'sTemp directory) Change temporary file storage directory: diskfileitemfactory.setrepository (file file) Fileitem.delete (): Deletes temporary files. Called after the stream is closed. 7, limit the type of upload files: only upload images: To determine the upload file extension + to determine the upload content MIME type 8, multi-file upload, the user did not pass the full if (Item.getname (). Equals ("")) {continue;} 9, File upload progress bar: Asynchronous communication with the server, the interval of communication to calculate the progress of the upload file ratio to servletfileupload register a listener.
2. File download and display list of uploaded files
One. Display the download page ListServlet1. Gets the Save resource path 2 in the server. Set up a map collection to store the UUID file name and the original file name 3. Traverse the resource path All files 3.1 Determine whether the file is a file, if it is a file, get the file name according to the delimiter separator gets the original file names, the UUID filename and the original filename are added to the Map collection 3.2 Otherwise is not a file, continue to recursively folder 4. Set the map to 5 in the request domain. Forward to show download list listfiles.jsp second, download list page design 1. Listfiles.jsp--> traverses the MAP2 in the Requestscope domain. Because the link resource has a file name, add each resource path to the <c:url> tag, note the actual path used here, so it is the value of key 3. Show downloads, connect to <c:url> label Connection Iii. Downloadservlet Class 1. Set the encoding problem to tell the browser output encoding format 2. Get the name of the file to be downloaded, encode and decode 3. Get the real path to the file by recreating the hashcode structure in directory 4. Create an input stream to associate the file 5. Get an output stream of 6. Copy the input stream into the output stream 7. Close stream, prompt for file download success
JavaMail Mail Development 1. e-Mail Development protocol
1. SMTP protocol: (focus)    the protocol for sending messages simple    message Transfer protocal    uses the port: 252. Pop protocol:    the protocol that receives the message    Post Office protocal    uses the port: 110
2. E-Mail Process understanding
In fact, you can understand the mail server as the Post office! If you need to send a letter to a friend, you need to put the letter in the mailbox so that your letter will "automatically" arrive at the post Office and the Post Office will mail it to the post office in another province. The letter will then be sent to the recipient's mailbox. The final addressee needs to check the mailbox regularly for new letters. In fact, each mail server consists of an SMTP server and a POP3 server, where the SMTP server is responsible for sending mail requests, and POP3 is responsible for receiving mail requests
3. Manually telnet to send and receive mail
Manually send an email (familiar with SMTP protocol) ready: [email protected] Iamsorryitheimacloud     axrozwltywnsb3vkiamsorry    awftc29ycnk= Smtp.163.com   the server that sent the message   smtp.qq.com    smtp.126.compop.163.com start sending: Telnet smtp.163.com---------------- -----------------The following content belonging to the SMTP protocol EHLO wyj          greet the server auth login             request authentication Axrozwltywnsb3vkawftc29ycnk=mail from:<[ Email protected]>rcpt to:<[email protected]>data               Identity message content starts (content needs to follow a certain format: RFC822 specification) From:[email protected] To:[email protected]subject:this is Test mailaaaaaaaaaaaaaaabbbbbbbbbbbbbbb.                   <cr><lf>: Quit----------------------------------on behalf of the end
4. JavaMail Overview and Precautions
1. JavaMail Overview Java mail is a mail-specific API provided by Sun, the main jar package: Mail.jar, activation.jar2. Precautions in MyEclipse, The class in the Javax.mail package is automatically imported to the Web project, but not all (actually only the interface, not the implementation class of the interface), so only the classes in MyEclipse cannot run the Java Mail project, But if you go back to importing Mail.jar yourself then there will be a conflict. Processing scheme: Find the Javaee.jar file in the path below and remove the Javax.mail!!! D:\Program files\myeclipse\common\plugins\com.genuitec.eclipse.j2eedt.core_10.0.0.me201110301321\data\ Libraryset\ee_5
5. Using Java to implement the mail sending process
1. Set up some necessary protocols, Remote mail server address Properties props = new properties ();p rops.setproperty ("Mail.transport.protocol", "SMTP"); Props.setproperty ("Mail.host", "smtp.163.com"); 2. According to the first step set the message sent by the relevant message, get a Session object <==> connect Session session = Session.getinstance (props); Session.setdebug (true); The user views the relevant code 3 for the underlying send message. Gets a Message object, Message object mimemessage msg = new MimeMessage (session), 3.1 sender Msg.setfrom (new internetaddress ("[Email Protected]); 3.2 Recipients Send to cc cc, BCC bccmsg.setrecipients (recipienttype.to, "[email protected]"), 3.3 subject Msg.setsubject (" Go mountain climbing tomorrow! "); 3.4 Body Msg.settext ("<a href= ' http:localhost:8080/day20_email/servlet/emailservlet?activecode=" +UUID.randomUUID (). ToString () + "' > Activate email address, to activate must first point me </a>"); 4. Create a mail sending object transport TP = Session.gettransport (); 4.1 Mail sending object (set login remote mail server account and password) tp.connect ("Itheimacloud", "IAmSorry"); 4.2 Send Tp.sendmessage (msg, msg.getallrecipients ()); 4.3 Mail send object to close Tp.close ();

Javaweb file upload and download & Mail Technology (18)

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.