File, FileReader and Ajax files upload instance Analysis (PHP) _javascript tips

Source: Internet
Author: User
Tags base64 file upload readfile
What can File FileReader do?
Ajax File Upload Example
The FileReader object can read the BASE64 encoded data (readasdataurl) of the file, the 2 binary string (readasbinarystring), the text (Readastext), and are all asynchronous.
Yes, email drag attachment upload can be used filereader with Ajax to complete.

File Object
The file object can be obtained from the input[type=file].files array and the drag-and-drop event event.dataTransfer.files.
The first picture is the file object under Chrome, and the 2nd image is the file object under Firefox. Firefox will be a few more methods, note that the method of reading data here is synchronized.




FileReader Objects
This is used to read the file data (and is asynchronous). The following is a simple code (the file object is obtained using the above method)
Copy Code code as follows:

var filereader = new FileReader ();
Filereader.onloadend = function () {
Console.log (this.readystate); This time it should be 2.
Console.log (This.result); Read completion callback function, data saved in result
}
filereader.readasbinarystring (file); Start reading 2 data asynchronous parameter to file object
Filereader.readasdataurl (file); Read Base64
Filereader.readastext (file)//Read text information

You can run the following simple example (Chrome and Firefox works)
Copy Code code as follows:

<! DOCTYPE HTML >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
&LT;TITLE&GT;HTML5 File and Filereader</title>
<link href= "Html/ui.css" _mce_href= "Html/ui.css" rel= "stylesheet"/>
<body>
<style type= "Text/css" ><!--
Box{background: #f8f8f8 border:1px solid #CCC;p Adding:10px;-webkit-box-shadow: #000 0px 0px 4px;-moz-box-shadow: #000 0px 0px 4px;
-webkit-border-radius:2px;font-family: ' Segoe UI ', Calibri, ' Myriad Pro ', Myriad, ' trebuchet MS ', Helvetica, Arial, sans- Serif
}
. bl{font-weight:700;}
. dl{padding:10px; border-top:1px dotted #999;}
. DL dd{padding:0; margin:0;}
. log{border:1px solid #CCC background: #f8f8f8; width:200px; position:absolute; right:10px; top:10px;
. log li{border:1p dotted #CCC; word-wrap:break-word;word-break:break-all; margin:0px; padding:0;}
. log ul{margin:0px; padding:0; list-style:none;}
--></style><style type= "Text/css" _mce_bogus= "1" ><!--
Box{background: #f8f8f8 border:1px solid #CCC;p Adding:10px;-webkit-box-shadow: #000 0px 0px 4px;-moz-box-shadow: #000 0px 0px 4px;
-webkit-border-radius:2px;font-family: ' Segoe UI ', Calibri, ' Myriad Pro ', Myriad, ' trebuchet MS ', Helvetica, Arial, sans- Serif
}
. bl{font-weight:700;}
. dl{padding:10px; border-top:1px dotted #999;}
. DL dd{padding:0; margin:0;}
. log{border:1px solid #CCC background: #f8f8f8; width:200px; position:absolute; right:10px; top:10px;
. log li{border:1p dotted #CCC; word-wrap:break-word;word-break:break-all; margin:0px; padding:0;}
. log ul{margin:0px; padding:0; list-style:none;}
--></style>
<div class= "box" id= "Baseinfo" >
<div></div>
</div>
<div class= "Log" >
<ul id= "Log" >
</ul>
</div>
<script type= "Text/javascript" ><!--
(function () {
Window.datavalue = 0;
var html = ' <dl class= ' DL ' >\
<dd>filename: $fileName $</dd>\
<dd>filetype: $fileType $</dd>\
<dd>filesize: $fileSize $</dd>\
<dd></dd>\
<dd>filebase64: <br/>\
<div style= "width:100%; height:100px; " > $fileBase 64$</div>\
</dd>\
</dl>\
'
var log = function (msg) {
console[' log '] (msg);
document.getElementById (' log '). InnerHTML + = ' <li> ' + msg + ' </li> ';
}

var DP = function () {
var defconfig = {
Dropwrap:window
}
This.init.apply (this, [Defconfig]);
This.file = null;
}
Dp.prototype = {
Init:function (args) {
var dropwrap = Args.dropwrap;
var _this = this;
Dropwrap.addeventlistener ("DragEnter", This._dragenter, false);
Dropwrap.addeventlistener ("DragOver", This._dragover, false);
Dropwrap.addeventlistener (' Drop ', function (e) {_this.readfile.call (_this,e)}, False);
Log (' Window Drop Bind--ok ');
},
_dragenter:function (e) {e.stoppropagation (); E.preventdefault ();},
_dragover:function (e) {e.stoppropagation (); E.preventdefault ();},
Readfile:function (e) {
E.stoppropagation ();
E.preventdefault ();
var dt = E.datatransfer;
var files = dt.files;
for (var i = 0; i< files.length;i++) {
var HTML = Html.slice ();
html = This.writeheader (Files[i], HTML);
This.read (Files[i], HTML);
}
},
Read:function (file, h) {
var type = File.type;
var reader = new FileReader ();
reader.onprogress = function (e) {
if (e.lengthcomputable) {
Log (' Progress: ' + Math.ceil (100*e.loaded/file.size) + '% ')
}
};
Reader.onloadstart = function (e) {
Log (' Onloadstart:ok ');
};
Reader.onloadend = function (e) {
var _result = E.target.result;
console[' log '] (e.target);
Log (' Data uri--ok ');
var d = document.createelement (' div ');
h = h.replace (' $fileBase 64$ ', _result);
if (/image/.test (File.type)) {
h = H.replace (' $data $ ', _result);
}
d.innerhtml = h;
document.getElementById (' Baseinfo '). appendchild (d);
};
Reader.readasdataurl (file); Base 64 encoding
Return
},
Writeheader:function (file, h) {
Log (file.filename + ' + ' + ' + (file.size/1024));
Return H.replace (' $fileName $ ', file.filename). Replace ("$fileSize $", (file.size/1024) + ' KB '). Replace ("$fileType $", File.type);
}
}
New DP ();
})()
--></script>
</body>

How to implement asynchronous file uploads
With the support of the file FileReader object, asynchronous file uploads will become simpler. (The form was previously submitted to the IFRAME for implementation)
1: Get the File object
2: Read 2 data
3: Simulate the HTTP request, send the data out (this is usually more troublesome)
Using the Sendasbinary method of XMLHttpRequest object to send data under Forefox;
4: Perfect Realization
problems encountered
Currently only Firefox can upload files correctly. (Chrome can also be picked Google.gears upload)
The file data read from Firefox and Chrome seems to be different (not sure if it's the reason for the debugging tools)
Chrome and other advanced browsers do not have the Sendasbinary method to send data only using the Send method, which may be the cause of the failure to upload correctly. (After testing normal text files can be uploaded correctly)
If you are interested?
Download this PHP environment test program, study how to implement other browser file upload

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.