Home >Web Front-end >JS Tutorial >JavaScript File API implements file upload preview_javascript skills
1. Overview
In the past, accessing local files was a headache for browser-based applications. Although JavaScript is playing an increasingly important role with the continuous development of Web 2.0 application technology, due to security considerations, JavaScript has always been unable to access local files. Therefore, in order to implement functions such as dragging and uploading local files in the browser, we have to resort to various technologies provided by specific browsers. For example, for IE, we need to use ActiveX controls to gain access to local files, and for Firefox, we also need to use plug-in development. Since the technical implementations of different browsers are different, in order for the program to support multiple browsers, our program will become very complex and difficult to maintain. But now, all this has been completely changed due to the emergence of File API.
File API is a draft submitted by Mozilla to W3C, aiming to launch a set of standard JavaScript APIs. Its basic function is to operate local files with JavaScript. For security reasons, this API only provides limited access to local files. With it, we can easily use pure JavaScript to read and upload local files. Currently, FireFox 3.6 is the first browser to support this feature. In addition, the latest versions of Google Chrome and Safari browsers also have corresponding support. The File API is expected to be part of the future HTML 5 specification currently being developed by the W3C.
2. File API Overview
The File API consists of a set of JavaScript objects and events. Gives developers the ability to manipulate files selected in the 9228385946262b90b0b620251f192b1f file selection control. Figure 1 shows the combination relationship of all JavaScript in the File API.
Type FileList contains a set of File objects. Usually FileList objects can be taken from the file field (7a282165fe11716a838bf671a5343150) in the form. A Blob object represents a set of raw binary streams that a browser can read. In the Blob object, the size attribute represents the size of the stream. The function slice() can split a long Blob object into small pieces. The File object inherits from the Blob object, and File-related properties are added to the Blob object. Among them, the attribute name represents the name of the file. This name removes the path information of the file and only retains the file name. The type attribute represents the MIME type of the file. The attribute urn represents the URN information of this file. To complete the file reading operation, a FileReader object instance is associated with a File or Blob object and provides three different file reading functions and 6 events.
The specific content of the file reading function:
readAsBinaryString() Read the file content, and the read result is a binary string. Each byte of the file will be represented as an integer in the range [0..255]. The function accepts a File object as parameter.
readAsText() Read the file content, and the read result is a string of text representing the file content. The function accepts a File object and the name of the text encoding as parameters.
readAsDataURL Read the file content, and the read result is a data: URL. DataURL is defined by RFC2397.
The specific content of the file reading event:
Event Name Event Description
Onloadstart Triggered when file reading starts.
Progress Triggered regularly when reading is in progress. The event parameters will contain the total amount of data read.
Abort Fired when the read is aborted.
Error Triggered when a reading error occurs.
Load Triggered when the read completes successfully.
Loadend Will be triggered when the read is completed, regardless of success or failure.
3. File API simple example
Next, we use a simple example to show the basic usage of File API. This example contains two code files, index.html contains the HTML code on the web side and JavaScript code for processing uploads; upload.jsp contains the code on the server side to receive uploaded files. Please see the sourcecode.zip in the attachment. In this example, we will display a traditional form with a File selection field. When the user selects a file and clicks submit, we use the File API to read the file content and upload the file to the server using Ajax through the XMLHttpRequest object. Figure 2 shows a screenshot of the demo in action.
We show the code step by step. Listing 1 shows the HTML portion of the code.
HTML portion of Listing 1 sample code
<body> <h1>File API Demo</h1> <p> <!-- 用于文件上传的表单元素 --> <form name="demoForm" id="demoForm" method="post" enctype="multipart/form-data" action="javascript: uploadAndSubmit();"> <p>Upload File: <input type="file" name="file" /></p> <p><input type="submit" value="Submit" /></p> </form> <div>Progessing (in Bytes): <span id="bytesRead"> </span> / <span id="bytesTotal"></span> </div> </p> </body>
As you can see, we use a normal ff9c23ada1bcecdd1a0fb5d5a0f18437 tag to include a traditional 0ac820164a0b3fea57ee8f01d9b5fa57 element. There is also a submit element inside ff9c23ada1bcecdd1a0fb5d5a0f18437. Outside the ff9c23ada1bcecdd1a0fb5d5a0f18437 there are 45a2772a6b6107b401db3c9b82c049c2 elements that represent the amount of data that has been read and the total amount. The action attribute of ff9c23ada1bcecdd1a0fb5d5a0f18437 points to a JavaScript function uploadAndSubmit(). This function completes the process of reading the file and uploading it. The function code is shown in Listing 2.
Listing 2 JavaScript function to read files and upload them
function uploadAndSubmit() { var form = document.forms["demoForm"]; if (form["file"].files.length > 0) { // 寻找表单域中的 <input type="file" ... /> 标签 var file = form["file"].files[0]; // try sending var reader = new FileReader(); reader.onloadstart = function() { // 这个事件在读取开始时触发 console.log("onloadstart"); document.getElementById("bytesTotal").textContent = file.size; } reader.onprogress = function(p) { // 这个事件在读取进行中定时触发 console.log("onprogress"); document.getElementById("bytesRead").textContent = p.loaded; } reader.onload = function() { // 这个事件在读取成功结束后触发 console.log("load complete"); } reader.onloadend = function() { // 这个事件在读取结束后,无论成功或者失败都会触发 if (reader.error) { console.log(reader.error); } else { document.getElementById("bytesRead").textContent = file.size; // 构造 XMLHttpRequest 对象,发送文件 Binary 数据 var xhr = new XMLHttpRequest(); xhr.open(/* method */ "POST", /* target url */ "upload.jsp?fileName=" + file.name /*, async, default to true */); xhr.overrideMimeType("application/octet-stream"); xhr.sendAsBinary(reader.result); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { console.log("upload complete"); console.log("response: " + xhr.responseText); } } } } } reader.readAsBinaryString(file); } else { alert ("Please choose a file."); } }
In this function, first we find the ff9c23ada1bcecdd1a0fb5d5a0f18437 element containing 9228385946262b90b0b620251f192b1f and find the d5fd7aea971a85678ba271703566ebfd element containing the uploaded file information. If the d5fd7aea971a85678ba271703566ebfd element does not contain a file, it means that the user has not selected any file, and an error will be reported.
Listing 3 Finding the d5fd7aea971a85678ba271703566ebfd element
var form = document.forms["demoForm"]; if (form["file"].files.length > 0) { var file = form["file"].files[0]; … … } else { alert ("Please choose a file."); }
Here, the object type returned from form[“file”].files is the mentioned FileList. We take the first element from it. After that, we build the FileReader object:
var reader = new FileReader();
When the onloadstart event fires, populate the 45a2772a6b6107b401db3c9b82c049c2 element on the page that represents the total amount of data read. See Listing 4
Listing 4 onloadstart event
reader.onloadstart = function() { console.log("onloadstart"); document.getElementById("bytesTotal").textContent = file.size; } 在 onprogress 事件触发时,更新页面上已读取数据量的 <span> 元素。参见清单 5
Listing 5 onprogress event
reader.onprogress = function(p) { console.log("onloadstart"); document.getElementById("bytesRead").textContent = p.loaded; }
In the final onloadend event, if there are no errors, we will read the file content and upload it through XMLHttpRequest.
Listing 6 onloadend event
reader.onloadend = function() { if (reader.error) { console.log(reader.error); } else { // 构造 XMLHttpRequest 对象,发送文件 Binary 数据 var xhr = new XMLHttpRequest(); xhr.open(/* method */ "POST", /* target url */ "upload.jsp?fileName=" + file.name /*, async, default to true */); xhr.overrideMimeType("application/octet-stream"); xhr.sendAsBinary(reader.result); … … } }
According to the specifications of the File API, we can also split the processing of the onloadend event into the processing of the event error and the event load.
In this example, we use a JSP in the background to handle the upload. The JSP code is shown in Listing 7.
Listing 7 Handling uploaded JSP code
<%@ page import="java.io.*" %><% BufferedInputStream fileIn = new BufferedInputStream(request.getInputStream()); String fn = request.getParameter("fileName"); byte[] buf = new byte[1024]; //接收文件上传并保存到 d:\ File file = new File("d:/" + fn); BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file)); while (true) { // 读取数据 int bytesIn = fileIn.read(buf, 0, 1024); System.out.println(bytesIn); if (bytesIn == -1) { break; } else { fileOut.write(buf, 0, bytesIn); } } fileOut.flush(); fileOut.close(); out.print(file.getAbsolutePath()); %>
在这段 JSP 代码中,我们从 POST 请求中接受文件名字以及二进制数据。将二进制数据写入到服务器的“D:\”路径中。并返回文件的完整路径。以上代码可以在最新的 Firefox 3.6 中调试通过。
四、使用拖拽上传文件
前面我们介绍了怎样通过 HTML5 的 File API 来读取本地文件内容并上传到服务器,通过这种方式已经能够满足大部分用户的需求了。其中一个不足是用户只能通过点击“浏览”按钮来逐个添加文件,如果需要批量上传文件,会导致用户体验不是很友好。而在桌面应用中,用户一般可以通过鼠标拖拽的方式方便地上传文件。拖拽一直是 Web 应用的一个软肋,一般浏览器都不提供对拖拽的支持。虽然 Web 程序员可以通过鼠标的 mouseenter,mouseover 和 mouseout 等事件来实现拖拽效果,但是这种方式也只能使拖拽的范围局限在浏览器里面。一个好消息是 HTML5 里面不仅加入了 File API,而且加入了对拖拽的支持,Firefox 3.5 开始已经对 File API 和拖拽提供了支持。下面我们先简要介绍一下拖拽的使用,然后用一个例子来说明如何通过拖拽上传文件。
1、拖拽简介
拖拽一般涉及两个对象:拖拽源和拖拽目标。
拖拽源:在 HTML5 草案里如果一个对象可以作为源被拖拽,需要设置 draggable 属性为 true 来标识该对象可作为拖拽源。然后侦听源对象的 dragstart 事件,在事件处理函数里设置好 DataTransfer。在 DataTransfer 里可以设置拖拽数据的类型和值。比如是纯文本的值,可以设置类型为"text/plain",url 则把类型设置为"text/uri-list"。 这样,目标对象就可以根据期望的类型来选择数据了。
拖拽目标:一个拖拽目标必须侦听 3 个事件。
dragenter:目标对象通过响应这个事件来确定是否接收拖拽。如果接收则需要取消这个事件,停止时间的继续传播。
dragover:通过响应这个事件来显示拖拽的提示效果。
drop:目标对象通过响应这个事件来处理拖拽数据。在下面的例子里我们将在 drop 事件的处理函数里获取 DataTransfer 对象,取出要上传的文件。
由于本文主要介绍 File API,对这部分不作详细解释,感兴趣的读者可以参考 HTML5 草案(见参考资料)。
2、拖拽上传文件实例
下面以一个较为具体的例子说明如何结合拖拽和 File API 来上传文档。由于直接和桌面交互,所以我们不需要处理拖拽源,直接在目标对象里从 DataTransfer 对象获取数据即可。
首先,我们需要创建一个目标容器用来接收拖拽事件,添加一个 div 元素即可。然后用一个列表来展示上传文件的缩略图,进度条及文件名。参见清单 8 的 HTML 代码和图 3 的效果图。详细代码请参见附件中的 dnd.html 文件。
清单 8 拖曳目标的 HTML 代码
<div id="container"> <span>Drag and drop files here to upload.</span> <ul id="fileList"></ul> </div>
拖拽目标创建好之后,我们需要侦听其对应的事件 dragenter,dragover 和 drop。在 dragenter 事件处理函数里,我们只是简单地清除文件列表,然后取消 dragenter 事件的传播,表示我们接收该事件。更加妥当的作法是判断 DataTransfer 里的数据是否为文件,这里我们假设所有拖拽源都是文件。dragover 事件里我们取消该事件,使用默认的拖拽显示效果。在 drop 事件里我们注册了 handleDrop 事件处理函数来获取文件信息并上传文件。清单 9 展示了这些事件处理函数。
清单 9 设置事件处理函数
function addDNDListeners() { var container = document.getElementById("container"); var fileList = document.getElementById("fileList"); // 拖拽进入目标对象时触发 container.addEventListener("dragenter", function(event) { fileList.innerHTML =''; event.stopPropagation(); event.preventDefault(); }, false); // 拖拽在目标对象上时触发 container.addEventListener("dragover", function(event) { event.stopPropagation(); event.preventDefault(); }, false); // 拖拽结束时触发 container.addEventListener("drop", handleDrop, false); } window.addEventListener("load", addDNDListeners, false);
处理 drop 事件
用户在拖拽结束时松开鼠标触发 drop 事件。在 drop 事件里,我们可以通过 event 参数的 DataTransfer 对象获取 files 数据,通过遍历 files 数组可以获取每个文件的信息。然后针对每个文件,创建 HTML 元素来显示缩略图,进度条和文件名称。File 对象的 getAsDataURL 可以将文件内容以 URL 的形式返回,对图片文件来说可以用来显示缩略图。要注意的一点是,在 drop 事件处理函数里要取消事件的继续传播和默认处理函数,结束 drop 事件的处理。清单 10 展示了 drop 事件的处理代码。
清单 10 drop 事件的处理
function handleDrop(event) { // 获取拖拽的文件列表 var files = event.dataTransfer.files; event.stopPropagation(); event.preventDefault(); var fileList = document.getElementById("fileList"); // 展示文件缩略图,文件名和上传进度,上传文件 for (var i = 0; i < files.length; i++) { var file = files[i]; var li = document.createElement('li'); var progressbar = document.createElement('div'); var img = document.createElement('img'); var name = document.createElement('span'); progressbar.className = "progressBar"; img.src = files[i].getAsDataURL(); img.width = 32; img.height = 32; name.innerHTML = file.name; li.appendChild(img); li.appendChild(name); li.appendChild(progressbar); fileList.appendChild(li); uploadFile(file, progressbar) } }
上传文件
我们可以通过 XMLHttpRequest 对象的 sendAsBinary 方法来上传文件,通过侦听 upload 的 progress,load 和 error 事件来监测文件上传的进度,成功完成或是否发生错误。在 progress 事件处理函数里我们通过计算已经上传的比例来确定进度条的位置。参见清单 11。图 4 展示了上传文件的效果图。
清单 11 上传文件
function uploadFile(file, progressbar) { var xhr = new XMLHttpRequest(); var upload = xhr.upload; var p = document.createElement('p'); p.textContent = "0%"; progressbar.appendChild(p); upload.progressbar = progressbar; // 设置上传文件相关的事件处理函数 upload.addEventListener("progress", uploadProgress, false); upload.addEventListener("load", uploadSucceed, false); upload.addEventListener("error", uploadError, false); // 上传文件 xhr.open("POST", "upload.jsp?fileName="+file.name); xhr.overrideMimeType("application/octet-stream"); xhr.sendAsBinary(file.getAsBinary()); } function uploadProgress(event) { if (event.lengthComputable) { // 将进度换算成百分比 var percentage = Math.round((event.loaded * 100) / event.total); console.log("percentage:" + percentage); if (percentage < 100) { event.target.progressbar.firstChild.style.width = (percentage*2) + "px"; event.target.progressbar.firstChild.textContent = percentage + "%"; } } } function uploadSucceed(event) { event.target.progressbar.firstChild.style.width = "200px"; event.target.progressbar.firstChild.textContent = "100%"; } function uploadError(error) { alert("error: " + error); }
本文通过对 File API 规范的讲解,以及两个展示其使用方法的例子,为大家提前揭示了作为未来 HTML5 重要组成部分的 JavaScript File API 的全貌。利用它,结合其他 HTML5 的新特性,比如 Drag&Drop,我们可以利用纯 JavaScript 方案,为用户提供更好使用体验的 Web 应用,与此同时,这样的一致化方案也使我们避免了以往跨浏览器支持所花费的巨大代价。相信 File API 的出现和广泛应用,将会是未来的 Web 2.0 应用的大势所趋。