How to read text file in client side via HTML5
In HTML4, As we known, if you want to read a local text file with javascript, you may need to use ActiveX object, there is a blog describes how to read text file by using ActiveX, clickhere. In other words, this solution cannot work on another browser, just like: Firefox, Opera, Safari, etc.
But now, we have HTML5, it supports we read local file via FileReader, it's an interface that provides methods to read file objects or blog objects into memory, it's asynchronous call.
OK, let me show how to read a local text file by using FileReader.
<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="jquery-1.4.4.min.js"></script> <script type="text/javascript"> /* * @description: read local text file via the html5 FileReader **/ function getFileContent(fileInput, callback) { if (fileInput.files && fileInput.files.length > 0 && fileInput.files[0].size > 0) { var file = fileInput.files[0]; if (window.FileReader) { var reader = new FileReader(); reader.onloadend = function (evt) { if (evt.target.readyState == FileReader.DONE) { callback(evt.target.result.split(',')[1]); } } reader.readAsDataURL(file); } } } function decode_base64(s) { var e = {}, i, k, v = [], r = '', w = String.fromCharCode; var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]]; for (z in n) { for (i = n[z][0]; i < n[z][1]; i++) { v.push(w(i)); } } for (i = 0; i < 64; i++) { e[v[i]] = i; } for (i = 0; i < s.length; i += 72) { var b = 0, c, x, l = 0, o = s.substring(i, i + 72); for (x = 0; x < o.length; x++) { c = e[o.charAt(x)]; b = (b << 6) + c; l += 6; while (l >= 8) { r += w((b >>> (l -= 8)) % 256); } } } return r; } $(function () { $('#b1').click(function () { // please do not use $('f1') to get the file dom element, otherwise, you'll get a js error. getFileContent(document.getElementById('f1'), function (str) { alert(decode_base64(str)); }); }); }); </script> </head> <body> <input type="file" id="f1" /> <input type="button" id="b1" value="read" /> </body> </html>
You need to run the above HTML page in IE9 or another browser which supports HTML5.
Attention please, because the reading action is asynchronous, so you need to call a callback function in onloadend event.
『Extending this topic』
- Methods of the FileReader interface
Function name Parameters Description readAsBinaryString file it reads file as binary code readAsText file, [encoding] it reads file as text readAsDataURL file it reads file as DataURL abort (none) interrupt reading
- Events of the FileReader interface
Event Description onabort it's triggered while interrupting reading onerror it's triggered while occurring error onloadstart it's triggered while starting reading onprogress it's triggered while processing reading onload it's triggered while finishing reading successful onloadend it's triggered while finishing reading, whatever successful or failed
You can read file as binary code or DataURL type, so you can do more optional things, for example, you can provide a download window via DataURL, and never go through the server side, if you want to know something about Data URI, clickhere, it introduces what'sData URI scheme.
And you also can read file content in client side, and display them, so that you have no need to upload them to server side just for file preview.
相關推薦
How to read text file in client side via HTML5
In HTML4, As we known, if you want to read a local text file with javascript, you may need to use ActiveX object, there is a blog descri
How to read a file bytes from a offset
example: public class IOUtil { public static byte[] readFile(String file) throws IOException { return readFile(new File(file)); }
How to execute sudo command in remote host via SSH
sed exec rac base should -s mach back sage Question: I have an interactive shell script, that at one place needs to ssh to another machin
How to send an SMS in Node.js via SMPP Gateway
How to send an SMS in Node.js via SMPP GatewayIntroductionSMPP (Short Message Peer-to-Peer) is a protocol used by the telecommunications industry. It excha
java 讀取配置文件工具類 (how to read values from properties file in java)
讀取 public resource fault .get exce ram trac stat Java 讀取配置文件工具類 使用 java.util.Properties import java.io.IOException; import java.io.Inpu
How to read *.data in Matlab and Python
See P2 of "HW2_545_2018_"In Matlab:z = dlmread('spambase.data',',');In Python:import numpy as npz = np.genfromtxt('spambase.data', dtype=float, delimi
How to read the environment variables in groovy email template 郵件模板中讀取系統環境變數
If you are using the email-ext Jenkins plugin to send out emails, there is a "build" object that contains a lot of information about your Jenkins job. I
How to setup Assigned Access in Windows 10 (Kiosk Mode) 設置分配的訪問權限(Kiosk模式)
win tar mode ctr assigned all oos rsquo eve Let’s say you’re building some sort of ingenious mechanical contraption to be dis
How to Catch Ctrl-C in Shell Script
con func sigint -c for r script init form target ref: https://stackpointer.io/script/how-to-catch-ctrl-c-in-shell-script/248/ #!/
Display certain line(s) from a text file in Linux.
statistic role n-1 mark art 2.7 box rtai ase Purpose: Display certain line or line
在pycharm中調試ryu應用(How to debug Ryu applications in Pycharm or other IDEs)
source deb python程序 mail log span cmd end pos 想要在IDE中使用IDE的調試功能來調試Ryu應用,可以這樣做: 新建一個python程序: 1 #!/usr/bin/env python 2 # -*- coding
How To Enable EPEL Repository in RHEL/CentOS 7/6/5?
1.7 like ons 64 bit pac PE ise nbsp ike What is EPEL EPEL (Extra Packages for Enterprise Linux) is open source and free community based r
How To Read A Paper
時間 記錄 文章 -s lar http split per 圖表 S. KeshavDavid R. Cheriton 科研工作者通常會花很多時間閱讀論文,然而研究者很少被閱讀技巧,浪費大量努力,作者在這篇文章裏介紹了他自己閱讀文獻的技巧,並可用來做文獻調研(litera
[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync
sync spa enc erro buffer ron div examples nbsp We‘ll read a csv file in node.js both synchronously, and asynchronously. The file we‘re re
How to setup kernel debug in Virtual Machine and redirect usermode debug sessions
轉載自:http://blog.sina.com.cn/s/blog_65e729050100m7on.html 在Windows高效排錯中提到了除錯重定向。書中沒有詳細介紹。今天恰好有機會在虛擬機器上從頭開始配置了一下,所以把詳細的內容記錄在這裡,算是補充。 文章本身使用英文寫的。由於書中是用
How to read version (and other) information from Android and iOS apps using Java
How to read version (and other) information from Android and iOS apps using Java https://medium.com/@mart.schneider/how-to-read-version-and-oth
How to remove ROM cfg in MAME
/usr/share/games/mame/roms/ /usr/local/share/games/mame/roms/ sudo rm /usr/local/share/games/mame/roms/* sudo cp -r /home/cuthead/Downloads/* /usr/local
How to save PNG file from NSImage (retina issues)
參考網址:https://stackoverflow.com/questions/17507170/how-to-save-png-file-from-nsimage-retina-issues /** 儲存指定大小圖片到本地路徑下 @param image image 實
How to get current timestamps in Java
How to get current timestamps in Java Timestamp timestamp = new Timestamp(System.currentTimeMillis());//2016-11-16 06:43:19.77 Here are two Java example
11.克服溝通障礙(How to break the bricks in conversation.)
1.What's this in English? 2.Can you speak slowly,I can't follow you.你能說慢點嗎?我跟不上你。 3.Pardon please.(請再說一次) 4.Sorry,I can't qu