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 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 () 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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



To learn more about open source, please visit: 51CTO Hongmeng Developer Community https://ost.51cto.com Running environment DAYU200:4.0.10.16SDK: 4.0.10.15IDE: 4.0.600 1. To create an application, click File- >newFile->CreateProgect. Select template: [OpenHarmony] EmptyAbility: Fill in the project name, shici, application package name com.nut.shici, and application storage location XXX (no Chinese, special characters, or spaces). CompileSDK10, Model: Stage. Device

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
