HTML5 + J2EE Implement Asynchronous file upload,

Source: Internet
Author: User

HTML5 + J2EE Implement Asynchronous file upload,

P.S. HTML5 was officially promoted after 8 years of hard work by W3C. The biggest part of this upgrade is to upgrade XMLHTTPRequest to XMLHTTPRequest Level II (what's strange about this ?). This object is now very powerful and may allow all users who use jQuery to regain the native ajax technology of HTML.

The theme goes on: what we want to achieve today is the following effect:

<Input type = "file" name = "fileToUpload" id = "fileToUpload" onchange = "fileSelected ();"/>

Select File. Here we see an onchange event. This is not a new event, but it is redefined in the HTML5 standard and called when the file is selected.

Function fileSelected () {// specifies the event var file = document. getElementById ('filetoupload '). files [0]; // obtain the file upload information if (file) {// if the user selects a file (if not selected, the file is null or undefined, so that you can determine) var fileSize = 0; // file size if (file. size> 1024*1024) // if the file size is greater than 1 MB fileSize = (Math. round (file. size * 100/(1024*1024)/100 ). toString () + 'mb '; // convert the file size and display else in MB. // otherwise, fileSize = (Math. round (file. size * 100/1024)/100 ). toString () + 'kb'; // otherwise, the document is displayed in KB. getElementById ('filename '). innerHTML = ''+ file. name; // display the file name information document. getElementById ('filesize '). innerHTML = ''+ fileSize; // displays the file size information document. getElementById ('filetype '). innerHTML = ''+ file. type; // display file MIME information }}

I didn't add this comment, and I don't know who added it ...... But you should be able to understand it.

Function uploadFile () {// The time when the upload button is clicked var fd = new FormData (); // FormData is a new class fd of html5. append ("file", document. getElementById ('filetoupload '). files [0]); // Add the file subject var file = document to the form data. getElementById ('filetoupload '). files [0]; // get the file subject var xhr = new XMLHttpRequest (); // initialize the ajax request xhr. upload. addEventListener ("progress", uploadProgress, false); // a new HTML5 event. When the upload progress changes, you can only call xhr when a file is uploaded. addEventListener ("Load", uploadComplete, false); // old event, xhr. addEventListener ("error", uploadFailed, false); // xhr when an error occurs. addEventListener ("abort", uploadCanceled, false); // var caption = document. getElementById ("caption "). value; // Title (irrelevant to file upload) fd. append ("filename", file. name); // Add the file name to form data fd. append ("filesize", file. size); // Add the file size to the form data fd. append ("filetype", file. type); // Add MIME to form data fd. append ("caption", capt Ion); // Add the title to the form data xhr. open ("POST", "FileUpload", true); // prepare for upload // xhr. setRequestHeader ("Content-Type", "multipart/form-data"); // This sentence cannot exist !!! I don't know why ...... Xhr. send (fd); // send a request}

After you click the upload button, this code is used. FormData is also a newly added object to store form data. (The Person Who adds the watch should be clear ......).

Next, let's look at the background. The background uses commonfileupload to receive messages (which seems to have been said ......), Paste the code first:

Package Upload; import java. io. file; import java. io. IOException; import java. io. printWriter; import java. util. iterator; import java. util. list; import javax. servlet. servletContext; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. fileupload. fileItem; import org. apac He. commons. fileupload. fileItemFactory; import org. apache. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; import Log. logManager; public class FileUpload extends HttpServlet {/*** Constructor of the object. */public FileUpload () {super ();}/*** Destruction of the servlet. <br> */p Ublic void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doPost method of the servlet. <br> ** This method is called when a form has its tag value method equals to post. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ Throws IOException if an error occurred */public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {request. setCharacterEncoding ("UTF-8"); DiskFileItemFactory fif = new DiskFileItemFactory (); fif. setSizeThreshold (1024*1024); ServletFileUpload sfu = new ServletFileUpload (fif); sfu. setSizeMax (1024*1024*1024); List items = null; try {ite MS = sfu. parseRequest (request);} catch (FileUploadException e) {// TODO Auto-generated catch block e. printStackTrace ();} Iterator iter = items. iterator (); String filename = ""; String filesize = ""; String filetype = ""; String caption = ""; FileItem fi = null; while (iter. hasNext () {FileItem item = (FileItem) iter. next (); if (item. isFormField () {String name = item. getFieldName (); if (name. equals ("filename") = True) {filename = item. getString ("UTF-8");} else if (name. equals ("filesize") = true) {filesize = item. getString ("UTF-8");} else if (name. equals ("filetype") = true) {filetype = item. getString ("UTF-8");} else if (name. equals ("caption") = true) {caption = item. getString ("UTF-8") ;}} else {fi = item ;}} ServletContext application = getServletContext (); String path = (String) application. getAttribute ("datapath") + "up Loadpath "+ application. getAttribute ("systempi") + filename; File f1 = new File (path); try {fi. write (f1);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); out. println ("You uploaded a file to the server, and the following will verify the information:"); out. println ("1. File Name:" + filename); out. println ("2. file size:" + filesize); out. println ("3. File MI ME type: "+ filetype); out. println (" if all the information is correct, the file is uploaded successfully! "); String sqls1 =" "; LogManager. log (" A File Upload request has been accepted! The file is stored in: "+ path); out. flush (); out. close ();} catch (Exception e) {LogManager. err (e. toString ();}/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occurs */public void init () throws ServletException {// Put your code here }}

It's quite simple, right? Processing HTML5 upload requests is basically the same as processing previous versions of upload requests. The only thing you need to note is that you used to splice requests. Therefore, the location is determined by you, now, the order of items in the string of the FormData splicing request is related to the append order, so do not make a mistake (it seems that I have made a mistake and added the file first, and then remedy it in the background ......).

Basically, this code is followed by adding file information to the database or something. Check the commonfileupload api in the upload procedure.

The entire project is not convenient for everyone to download, but it is in an OJ project. If you are interested, please pay attention to entering the project's git. In addition, if you reprint it, please note it. Thank you!

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.