- <! DOCTYPE HTML>
- <html>
- <head>
- <meta charset="UTF-8">
- <link href=". /resources/css/common.css " rel="stylesheet " />
- <script src=". /resources/js/jquery-2.1.4.js "></script>
- </head>
- <body>
- <h2>html5 asynchronous upload file with progress bar </H2>
- <form method="POST" enctype="Multipart/form-data">
- Other information to submit:<input type="text" name="Otherinfo"/><br/> <br/>
- Select the file to upload:<br/>
- < Input type= "file" name = "file" />< span></span ><br/>
- <input type="file" name="file" /><span></span ><br/>
- </form>
- <br/><br/>
- <input type="button" value= "upload Bar" onclick="upload ()"/>
- <br/><br/>
- Upload progress:<progress></Progress><br/>
- <p id="Progress">0 bytes</P>
- <p id="info"></P>
- </body>
- <script>
- var totalsize = 0;
- A handler for the onchange event that binds all type=file elements
- $ (': File '). Change (function () {
- var file = This.files[0]; //Assuming that the file tag does not have the Multiple property open, then just take the first one.
- name = File.name;
- size = File.size;
- Type = File.type;
- url = window. Url.createobjecturl (file); //Get the URL of the local file, if it is a picture file, can be used to preview the picture
- $ (this). Next (). HTML ("FileName:" + name + "file type:" + type + " File Size:" + size + "url:" + URL);
- TotalSize + = size;
- $ ("#info"). HTML ("Total size:" + totalsize + "bytes");
- });
- function upload () {
- Creates a Formdata object that is initialized to the data in the form form. You need to add additional data to use Formdata.append ("property", "value");
- var formData = New FormData ($ (' form ') [0]);
- Ajax asynchronous uploads
- $.ajax ({
- URL: "Http://localhost:8080/MyJavaStudio/servlet/file/upload",
- Type: "POST",
- Data:formdata,
- XHR: function () { //Gets the XHR object in Ajaxsettings, binds the handler for the Progress event for its upload property
- MYXHR = $.AJAXSETTINGS.XHR ();
- if (myxhr.upload) { //Check if upload property exists
- callback function for binding progress event
- MyXhr.upload.addEventListener (' progress ', progresshandlingfunction, false);
- }
- return MYXHR; //XHR object returned to jquery using
- },
- Success: function (Result) {
- $ ("#result"). HTML (result.data);
- },
- ContentType: false, //must be false to automatically add the correct content-type
- ProcessData: false //must be false to avoid jquery's default handling of Formdata
- });
- }
- Upload Progress callback function:
- function Progresshandlingfunction (e) {
- if (e.lengthcomputable) {
- $ (' progress '). attr ({value:e.loaded, max:e.total}); //Update data to progress bar
- var percent = e.loaded/e.total*100;
- $ (' #progress '). HTML (e.loaded + "/" + e.total+"bytes." + percent.tofixed (2) + "%");
- }
- }
- </script>
- </html>
HTML5 jquery+formdata Asynchronous upload file with progress bar