File Upload with XMLHttpRequest

Source: Internet
Author: User

Microsoft first introduced the XMLHttpRequest object in the form of the ActiveX object in the IE5, after the development of Google, all the browsers have now supported XMLHttpRequest, the current internet is developing XMLHttpRequest Level 2 draft, compared to the original XMLHttpRequest, the new standard XMLHttpRequest has been greatly improved, providing a lot of new features.

This article makes a simple comparison of the new and old XMLHttpRequest objects, and introduces the improvement of the new standard XMLHttpRequest object.

Disadvantages of the original XMLHttpRequest object:

1. Only text data is supported for delivery, and binary data is not supported.

2. When the data is passed, there is no progress event and the progress information of the delivery is not displayed in real time.

3. Cross-domain requests cannot be sent under the same-origin policy.

XMLHttpRequest improvements to the new standard:

1. Binary data can be passed.

2. Cross-domain data can be obtained when the server-side is set to allow cross-domain requests.

3. You can use native Formdata objects to manage the form data that you want to send.

4. The progress event is provided to provide progress information. When downloading and uploading, there are progress events, when downloading, the progress event is triggered by XMLHttpRequest itself and uploaded by the Xmlhttprequest.upload object.

Using the new standard XMLHttpRequest object, we can implement the file Ajax upload function very conveniently.

Html:

<! DOCTYPE html><p id= "Info" ></p></div><script src= "./js/upload.js" ></script></body></ Html>

Javascript:

The specific code for Upload.js is as follows:

var button = Document.queryselector ("#btn-upload"), input = Document.queryselector ("#ipt-file"), progress = Document.queryselector ("#progress"), info = document.queryselector ("#info"), var upload = function () {if ( Input.files.length = = = 0) {console.log ("File not selected"); return;} var formData = new FormData (), Formdata.append ("file", Input.files[0]), var xhr = new XMLHttpRequest (); Xhr.onreadystatechange = function () {if (xhr.readystate = = = 4) {console.log (xhr.responsetext); info.innerhtml = Xhr.responsetext;}}; Xhr.upload.addEventListener ("Progress", function (event) {progress.style.width = Math.ceil (event.loaded * 100/ event.total) + "%";}, False); Xhr.open ("POST", "./upload"); Xhr.send (formData);}; Button.addeventlistener ("Click", Upload, false);

Java:

The upload server is implemented using Servlets.

Package Com.servlet;import Java.io.file;import java.io.printwriter;import java.util.iterator;import java.util.List; Import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet (description = "File Upload", Urlpatterns = {"/upload"} public class Uploadservlet extends HttpServlet {private static final long Serialversionuid = 1l;private String filepath;p rivate int maxfilesize = 1024x768 * 1024;public void init () {FilePath = This.getservletcontext (). Getrealpath ("/") + File.separ ator+ "Upload"; File File = new file (FilePath), if (!file.exists ()) {file.mkdirs ();}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Java.io.IOException {response.setcontenttype ("Text/plain"); Response.setcharacterencoding ("Utf-8"); PrintWriter out = Response.getwriter ();D iskfileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory); Upload.setsizemax (maxfilesize); try {List fileitems = Upload.parserequest (Request), Iterator i = Fileitems.iterator (), while (I.hasnext ()) {Fileitem fi = (Fileitem) i.next (); if (!fi.isformfield ()) {String fileName = Fi.getname (); File File = new file (FilePath + file.separator + fileName); fi.write (file); Out.println (FileName + upload success);}}} catch (Exception ex) {out.println ("Upload file failed:" + ex.getmessage ());} finally {out.close ();}}}

  

  

  

File Upload with XMLHttpRequest

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.