HTML5 and Ajax work together to interpret file uploads,
In the previous article "Practical HTML5 applications: Flexible Drag of Files", we learned how to drag files to a browser using HTML5, read the type of the dragged file and other file-related information. This article describes how to use Ajax and HTML5 to asynchronously upload files to the server. The settings on the upload form page are described in the following code: <form id = "upload" action = "upload. php "method =" POST "enctype =" multipart/form-data "> <Fieldset> <Legend> HTML File Upload </legend> <Input type = "hidden" id = "MAX_FILE_SIZE" name = "MAX_FILE_SIZE" value = "300000"/> <Div> <Label for = "fileselect"> Files to upload: </label> <Input type = "file" id = "fileselect" name = "fileselect []" multiple = "multiple"/> <Div id = "filedrag"> or drop files here </div> </Div> <Div id = "submitbutton"> <Button type = "submit"> Upload Files </button> </Div> </Fieldset> </Form>
Here, we set the form submission to upload. php to process uploaded files. In the form, the size of the uploaded image cannot exceed 300 kb. The uploaded Javascript code is as follows: // File selection Function FileSelectHandler (e ){ // Cancel event and hover styling FileDragHover (e ); // Fetch FileList object Var files = e.tar get. files | e. dataTransfer. files; // Process all File objects For (var I = 0, f; f = files; I ++ ){ ParseFile (f ); UploadFile (f ); } }
In the previous tutorial, we have introduced ParseFile (f). Now let's focus on the code of UploadFile. The Code is as follows:Function UploadFile (file ){
Var xhr = new XMLHttpRequest ();
If (xhr. upload & file. type = "image/jpeg" & file. size <= $ id ("MAX_FILE_SIZE"). value ){
// Start upload
Xhr. open ("POST", $ id ("upload"). action, true );
Xhr. setRequestHeader ("X_FILENAME", file. name );
Xhr. send (file );
}
}
In the above Code, the XmlHttpRequest2 object currently only supported in FireFox and Chrome is used. XmlHttpRequest2 is an enhancement to xmlhttprequest, which is familiar to everyone. It is not finalized yet. For details, refer to explain. In the code above, the first step is to determine whether the type of the uploaded file is an image file and whether the size meets the requirements. If yes, call the send method to send the file to the server, in addition, the HTTP File Header X_FILENAME is set as the uploaded file name. In the PHP server code, the HTTP header is used to determine whether AJAX or normal form upload is used. |
Http://html5.662p.com/thread-45-1-1.html