Upload files without refreshing and implement in HTML5

Source: Internet
Author: User
Tags readfile

General implementation method:

Ajax cannot upload files. Therefore, to do this without refreshing a new file, you need to hide an iframe on the page and then direct the target of the uploaded form to this iframe, implementation in disguise. The following code:

<p id="uploading" style="display:none;">Uploading...<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >    File: <input name="myfile" type="file" />          <input type="submit" name="submitBtn" value="Upload" /></form><iframe id="upload_target" name="upload_target" src="#" style=";height:0;border:0px solid #fff;"></iframe>

Upload_target Is An iframe with a length and width of 0, so it cannot be seen on the page. We also need to work with js to make the results better:

<Script> function startUpload () {$ ('# uploading '). show ();} function finisheUpload (I) {$ ('# uploading '). hide (); if (I = 0) {alert ("uploaded successfully") ;}else {alert ("failed to upload") ;}</script>

The startUpload method is triggered when a form is submitted. Because there is no callback function, finisheUpload can only be controlled by the output of the upload. php file. Usually, a piece of javascript code is output in the output for execution.

The php code is as follows:

<?phpheader("Content-Type:text/html;charset=utf-8");$destination_path = getcwd().DIRECTORY_SEPARATOR;$filname = $destination_path . basename( $_FILES['myfile']['name']);$filname=iconv("UTF-8","gb2312",$filname);if(move_uploaded_file($_FILES['myfile']['tmp_name'], $filname)) {   echo "<script language=\"javascript\" type=\"text/javascript\">window.parent.finisheUpload(0);</script> ";}else{   echo "<script language=\"javascript\" type=\"text/javascript\">window.parent.finisheUpload(1);</script> ";}


Note: When outputting javascript, because the called js method is defined outside iframe, you must specify window. parent to call the js method within iframe.

--------

Implementation Method in HTML5:

First, we will introduce the FileReader object:

For details about the FileReader object, refer to the W3C official documentation.

This interface provides methods to read file objects or Blob objects. It inherits EventTarget, and the interface description is as follows:

[Constructor]    interface FileReader: EventTarget {      // async read methods      void readAsArrayBuffer(Blob blob);      void readAsText(Blob blob, optional DOMString label);      void readAsDataURL(Blob blob);      void abort();      // states      const unsigned short EMPTY = 0;      const unsigned short LOADING = 1;      const unsigned short DONE = 2;      readonly attribute unsigned short readyState;      // File or Blob data      readonly attribute (DOMString or ArrayBuffer)? result;      readonly attribute DOMError? error;      // event handler attributes      attribute EventHandler       attribute EventHandler onprogress;      attribute EventHandler       attribute EventHandler onabort;      attribute EventHandler onerror;      attribute EventHandler     };

There are four asynchronous methods, three of which are reading, one is giving up, four state attributes, one result, one error, and six events. The readAsBinaryString method has been removed by W3C before.) The trigger time of these six events is as follows:

Loadstart -- When the read starts.

Progress -- While reading (and decoding) blob

Abort -- When the read has been aborted. For instance, by invoking the abort () method.

Error -- When the read has failed (see errors ).

Load -- When the read has successfully completed.

Loadend -- When the request has completed (either in success or failure ).

The following example shows how to read a text document and read the content from alert.

<Script> function readfile (dom) {var file = dom. files [0]; var textType =/text. * // regular expression to match text/html, text/plain if (file. type. match (textType) {var reader = new FileReader (); // register the event function, that is, the reader to do after reading the content. onload = function (e) {alert (reader. result);} // reader asynchronously reads the content. readAsText (file, 'gb2312'); $ ("# msg" ).html ("Asynchronous reading in progress");} else {alert ("file not supported ");}} </script> <input type = "file" id = "testfiles" name = "files []" onchange = "readfile (this ); "/> <div id =" msg "> </div>

------------------------------

The following is an example. to read a DataURL, DataURL is actually a DataURI. To learn more about the URI, go to http://css-tricks.com/data-uris/, and retrieve more information ). It provides a way to display data in a browser. For example, if you want to display a picture of Baidu logo, you can write it as follows:

 

You can also use its URI to write, as shown below:

The string entered in src is DataURI in the following format:

Data: [<mime type>] [; charset = <charset>] [; base64], <encoded data>

This type of URI is actually very useful. It can reduce HTTP requests and speed up the website. Therefore, after obtaining the URI, you can load the local image. The sample code is as follows:

<Script> function loadimg (dom) {var file = dom. files [0]; // regular expression to match var imageType =/image, such as image/jpeg. */; if (file. type. match (imageType) {var reader = new FileReader (); reader. onload = function (e) {var img = new Image (); img. src = \ '# \' "$ (" # divimg "). append (img);} reader. readAsDataURL (file) ;}else {alert ("file not supported ");}} </script> <input type = "file" id = "testfiles" name = "files []" onchange = "loadimg (this ); "/> <div id =" divimg "> </div>


------------------------------------

Another method is readAsArrayBuffer. It can be seen from the literal that the file is read to an array buffer.

Use readAsArrayBuffer to upload files

The following is an example:

<Script> function upload () {var file = $ ('# testfiles') [0]. files [0]; var reader = new FileReader (); reader. onload = function (rResult) {var filename = file. name; var options = {type: 'post', url: 'upload. php? Filename = '+ filename, data: reader. result, success: function (result) {alert (result. msg) ;}, processData: false, // tell jQuery not to process the sent data contentType: false, // tell jQuery not to set the Content-Type Request Header dataType: "json"}; $. ajax (options) ;}; reader. readAsArrayBuffer (file) ;}</script> <input type = "button" value = "upload" onclick = "javascript: upload ();"/>

Backend PHP code:

Try {$ filename = $ _ GET ['filename']; $ input = file_get_contents ("php: // input"); // This is the InputStream that gets the request, file_put_contents ($ filename, $ input) in PHP; // save it as a file. Echo json_encode (array ("msg" => "uploaded");} catch (Exception $ e) {echo json_encode (array ("msg" => "Upload Failed "));}


FormData Method

FromData official description is here. ExploitationFormDataObject, you can use a series of key-value pairs to simulate a complete form.

The following example shows how to upload multiple files:

<Script> function upload () {var formdata = new FormData (); $. each ($ ('# testfiles') [0]. files, function (I, file) {formdata. append ('file-'+ I, file) ;}); var options = {type: 'post', url: 'upload. php ', data: formdata, success: function (result) {alert (result. msg) ;}, processData: false, // tell jQuery not to process the sent data contentType: false, // tell jQuery not to set the Content-Type Request Header dataType: "json"}; $. ajax (options) ;}</script> <input type = "button" value = "upload" onclick = "javascript: upload ();"/>


Background PHP code:

Try {foreach ($ _ FILES as $ key => $ value) {// print_r ($ _ FILES [$ key]); echo "<br> "; move_uploaded_file ($ value ["tmp_name"], $ value ['name']);} echo json_encode (array ("msg" => "uploaded "));} catch (Exception $ e) {echo json_encode (array ("msg" => "Upload Failed "));}



Reference:

Https://developer.mozilla.org/zh-CN/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

Http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

Http://www.w3.org/TR/XMLHttpRequest2/#interface-formdata

Http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

Http://www.dotblogs.com.tw/junegoat/archive/2013/05/27/test-fileapi-multiupload-readasarraybuffer.aspx

This article is from the "one blog" blog, please be sure to keep this source http://cnn237111.blog.51cto.com/2359144/1330089

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.