Home > Web Front-end > JS Tutorial > body text

File, FileReader and Ajax file upload example analysis (php)_javascript skills

WBOY
Release: 2016-05-16 18:07:13
Original
2035 people have browsed it
File What can FileReader do?
Ajax file upload example
FileReader object can read the Base64 encoded data of the file (readAsDataURL), binary string (readAsBinaryString), text (readAsText) and all asynchronously.
By the way, you can use FileReader and Ajax to upload email attachments by dragging and dropping them.

File object
File object can be obtained from the input[type=file].files array, and the drag event event.dataTransfer.files.
The first picture is the File object under Chrome, and the second picture is the File object under Firefox. There will be several more methods under Firefox. Note that the data reading methods here are synchronous.

File, FileReader and Ajax file upload example analysis (php)_javascript skills

File, FileReader and Ajax file upload example analysis (php)_javascript skills
FileReader object
This is used to read file data (and is asynchronous). The following is a simple code (the file object is obtained using the above method)
Copy code The code is as follows:

var fileReader = new FileReader();
fileReader.onloadend = function(){
console.log(this.readyState); // This time should be 2
console.log(this. result); Reading completion callback function, the data is saved in result
}
fileReader.readAsBinaryString(file);//Start reading binary data asynchronously. The asynchronous parameter is the file object
//fileReader.readAsDataURL (file); //Read Base64
//fileReader.readAsText(file);//Read text information

You can run the following simple example (valid for chrome and firefox)
Copy code The code is as follows:





html5 File and FileReader





(把图片拖拽到这里)利用 FileReader 获取文件 base64 编码












如何实现异步文件上传
有了File FileReader 对象的支持,异步文件上传将变得简单。(以前都会把form提交到iframe来实现)
1:取得File对象
2:读取2进制数据
3:模拟HTTP请求,把数据发送出去(这里通常比较麻烦)
在forefox下使用 XMLHttpRequest 对象的 sendAsBinary 方法发送数据;
4:完美实现
遇到的问题
目前仅有 firefox 可以正确上传文件。(Chrome也可以采google.gears上传)
对于从firefox和chrome下读取到的文件数据好像不一样(不知道是否是调试工具的原因)
Chrome以及其他高级浏览器没有 sendAsBinary 方法 只能使用 send 方法发送数据,有可能是上面的原因导致无法正确上传。(经过测试普通文本文件可以正确上传)
如果你有兴趣?
下载这个PHP环境的测试程序,研究下如何实现其他浏览器的文件上传  
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!