For a long time, developers have been distressed by this. Most of them have used Flash as solutions for solving this problem, but Flash is not a piomacetizer. Because of the Flash version, problems caused by cutting sometimes become nightmares. Some websites use the enableype = Multipart/Form-Data attribute of Form tag, but this attribute requires the server to make special settings to display the progress, and it is also complicated. Complicated means that it is easy to make mistakes. This is not us. What you want.
Now let's see why HTML5 can solve this problem, and how well it can do.
Upload files with html5In the HTML5 standard, the XMLHTTPREQUEST object is redefined, known as XMLHTTPRequest Level 2, which contains the following 5 new features:
1. Support upload and download bytes, such as files, blobs, and form data
2. Added the progress of uploading and downloading
3. Support of cross -domain requests
4. Allow an anonymous request (that is, the referr part that does not send HTTP)
5. Allow the timeout of the request
In this tutorial, we mainly pay attention to the first and second features, especially the second item-it can provide the upload progress we want. Unlike the previous plan, this solution does not require the server to make special settings, so everyone can try it by looking at the tutorial.
The above diagram is the content we can achieve:
1. Display the uploaded file information, such as file name, type, size
2. A progress bar that can show real progress
3. The speed of uploading
4. Estimation of the rest of the time
5. The amount of data that has been uploaded
6. The response of the server returned after the upload is over
In addition, with XMLHTTPREQUEST, our upload process is asynchronous, so when the user uploads the file, it can still operate other elements in the webpage, and there is no need to wait for uploading to complete. After the upload is over, we can get the response from the server back, so the entire upload process is quite logical.
HTML5's progress eventHTML5 adds a new progress event, which provides us with the following information:
1. Total -file size
2. Loaded -The size of the uploaded
3. LengthComputable -Whether the progress can be calculated
There is not much information, but it is enough to calculate the progress of the file. Of course, there are still many things it does not give directly, which is a pity.
HtmlIt is not much different from ordinary file upload code. However, note that the input tag associates a JavaScript function on Onchange.
<! Doctype html> <html> <head> <Title> Upload files with xmlhttprequest </head> <body> <form ID = Form1 EnCTYPE = Multipart/Form-Data Method = Post Action = upload.php> <div class = row> <label for = filetoupload> select a file to upload </label> <input type = file name = filetoupload id = filetoupload = fileselec Ted ();/> </DIV> <div ID = FILENAME> </div> <div ID = Filesize> </div> <div ID = FileType> </DIV> <DIV Class = Row> <input Type = Button Onclick = UPLOADFILE () Value = UPLOAD/> > << divJavascript
Once we use INPUT in HTML, we can get a FileList object in the JS code. This object is part of the newly added file API in HTML5. Each FileList object is a set of a set of file objects, and the file object has the following attributes:
1. name - file name (does not include path)
2. Type -file type (lowercase)
3. SIZE -file size (unit is byte)
This is exactly what we need. Of course, HTML5 also has a Filereader object, but we did not use it here. Now, through the above three contents, we can control the size and file types uploaded by the user in order to reduce the pressure during the server and improve the security factor.
function filected () {var file = document.GetelementByid ('filetoupload'). Files [0]; if (file) {var filesize = 0; if (file.size> 1024 * 1024) ze = (math.round (file .size * 100 / (1024 * 1024)) / 100) .tring () + 'mb'; Else Filesize = (math.round (file.size * 100 /1024) / 100) .tring () + ') ; Document.GetelementByid ('FILENAME'). Innerhtml = 'name:' + file.name; Document.GetelementByid ('Filesize'). Innerhtml = 'Size:' + Fi lesize; document.GetelementByid ('Filetype'). InnerHtml = 'Type:' + File.type;}}
So what will happen when the user chooses a good file and click Upload?
Function uploadfile () {var xhr = new xmlhttpRequest (); var fd = document.GetelementByid ('Form1'). Getformdata (); Ad.addentListener (progress, uploadprogress, false); xhr. addeventristener (load, uploadComplete, false); XHR.AdDeventListener (ERROR, UploadFaILED, FALSE); se); / * Be Sure to Change The URL Below to the URL of Your Upload Server SIDE SIDE SIDE SIRIPT * / xhr.open (post, upload.php); xhr.send (fd);} Function Uploadprogress (EVT) {if (EVT.LengthComputable) {Var PercentComplete = Math.Round. Loaded * 100 / EVT.TOTAL) ; Document.GetelementByid ('ProgressNumber'). InnerHtml = PercentComplete.tostring () + '%';} Else {document.gtelementByid ('ProgressNumber ') .innerhtml =' Unable to Compute ';}} Function uploadComplete (EVT) { / * This event is raised when the server send back a response */ alert (evt.target.Responsetext); empting to upload the file.);} Function uploadCanceled (EVT ) {alert (the upload has ben can captain by the user or the browser dropped the connection.);}
In the second line of code, our JS code uses another new object -FormData launched by another HTML5. The FormData object is the set of the user's form data. It stores the form data in the form of key value pair, and its value can include numbers, string, and files. We submit data to the server by turning this object.
Of course, we can also build this object manually in the code, for example, like the following:
var fd = new formData (); fd.append (Author, Shiv Kumar); FD.APPEND (name, html 5 file API/FormData); fd.append (Filetoupload, Document.GetelementByid ( 'filetoupload'). Files [0 ]);
Back to the topic. Looking back at the previous code, we added many event monitoring of XMLHTTPREQUEST. The purpose is to obtain the real situation of uploading files. In particular, it is important to note that what we are linking is not XMLHTTPRequest itself, but its attributes, such as uploadprogress.
Complete codeFinally, take a look at the complete code.
<! Doctype html> <HTML> <Head> <Title> Upload Files USING XMLHTTPREQUEST -Minimal </Title> <Script Type = Text/Javascript> Flesented Fileselect () {var file = document.GetelementByid ('Filetoupload'). Files [0]; if (file) {var filesize = 0; if (file.size> 1024 * 1024) filesize = (math.round (file.size * 100 / (1024 * 1024)) .tring () .tring () + 'Mb'; else filesize = (math.round (file.size * 100 /1024) / 100) .tring () + 'kb'; document.Getelementbyid ('FILENAME'). Innerhtml = E: ' + File .name; document.GetelementByid ('Filesize'). InnerHtml = 'Size:' + Filesize; Document.GetelementByid ('FileType'). + file.type;}} Function uploadFile () {var FD = new formData (); fd.append (filetoupload, document.getelementbyid ('filetoupload'). Files [0]); Var xhr = new xmlhttpRequest (); xhr.upload. addeventristener (progress, uploadprogress, false); xhr. addeventristener (load, uploadComplete, false); XHR.AdDeventListener (ERROR, UploadFaILED, FALSE); se); xhr.open (post, uploadminimal.aspx); xhr.send (fd);} Function UploadProgress (EVT) {if (EVT.LengthComputable) {var percentcomplete = math.round (ev.loaded * 100 / evt.total); 'ProgressNumber'). Innerhtml = PercentComplete.tring () + '% ';} Else {Document.GetelementByid (' ProgressNumber '). InnerHtml =' Unable to Compute '; s raised when the server send back a response */ alert (evt.target .Responsetext);} Function uploadFailed (EVT) {Alert (there was an error attempting to upload the file.); E UPLOAD HAS Been Canceled by the User or The Browser Dropped the Connection.) ;} </script> </head> <boody> <FORM ID = FORM1 Enctype = Multipart/Form-Data Method = Post Action = UPLOAD.PHP> <DIV Class = Row> <Label = Filetoup load> select a file to Upload </label> <input type = file name = filetoupload id = filetoupload onchange = fileselect ();/> </div> <div ID = filename> </div> <div ID = fi lesize> </div> <div ID = FileType> </DIV> <DIV Class = ROW> <input Type = Button Onclick = UploadFile () Value = Upload/> </div m> </body > </html>
Is our task completed? It can be said that it is complete, because this code has been able to complete the task of uploading files, and it can also display the progress of uploading; but it should be said that we do not, because except for this skeleton HTML, we have many things that have not been done, such as CSS, such as CSS Beautify and so on. But this is not the theme of our article.
Finally, remind you that the code of the tutorial should be operated on the browser that supports the new features. If you don't know if your browser supports, you can check here.
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.