In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
File
File API adds some interfaces to directly access file information on the basis of the file input fields in the form. HTML5 adds a files collection to the file input elements in DOM. When one or more files are selected through the file input field, the files collection contains a set of File objects, one for each File object. Each File object has the following read-only properties
Name: file name in the local file system
Size: the byte size of the file
Type: string, MIME type of the file
LastModifiedDate: string, when the file was last modified
You can know the information of each selected file by listening for change events and reading the files collection.
File1.onchange = function () {var data = file1.files [0]; result [XSS _ clean] = 'type:' + data.type +'
Size:'+ data.size +'(bytes)
Name:'+ data.name +'
Modification time:'+ data.lastModifiedDate;}
[hide file input]
Modern browsers support hiding the default file input box elements and using a custom interface to act as a button to open the file selection dialog box. It's easy to implement, just use style display:none to hide the original file input box, and then call its click () method when needed.
[note] IE9- browsers do not support
Button btn.onclick = function () {file1.click ();} file1.onchange = function () {result [XSS _ clean] = file1.files [0] .name;}
FileReader
The function of File API is more than that. Through the FileReader type it provides, you can even read data in files.
[constructor]
Use the FileReader () constructor to create a FileReader object
Var reader = new FileReader ()
[attribute]
Error: indicates an error that occurred while reading the file (read-only)
ReadyState: indicates the current state of the FileReader object, and the value is one of the state constants (read-only)
There are three state constants
Constant name value describes that EMPTY 0 has not loaded any data LOADING 1 data is being loaded DONE 2 has completed all read requests
Result: indicates the contents of the file read, this property is valid only after the read operation is complete, and the format of the data depends on which method the read operation was initiated (read-only)
[methods]
The FileReader type implements an asynchronous file reading mechanism. Think of FileReader as XMLHttpRequest, except that it reads the file system, not the remote server. To read the data in a file, FileReader provides the following methods
Abort (): aborts the read operation
ReadAsText (file or Blob,encoding): reads the contents of a File or Blob object in plain text and saves the read text in the result property. The second parameter (optional) is used to specify the encoding type. Default is UTF-8.
ReadAsDataURL (file or Blob): reads the contents of a File or Blob object and saves the file in the result property in the form of data URI (Base64 encoding)
ReadAsBinaryString (file or Blob): reads the contents of a File or Blob object and saves a string in the result property, with each character in the string representing a byte
ReadAsArrayBuffer (file or Blob): reads the contents of a File or Blob object and saves an ArrayBuffer containing the contents of the file in the result property
[note] IE browsers do not support the readAsBinaryString () method
These methods of reading files provide great convenience for flexible processing of file data. For example, an image file can be read and saved as data URI so that it can be displayed to the user, or for ease of parsing, the file can be read as text
[event]
Because the read process is asynchronous, FileReader also provides several events
Onabort: called when a read operation is aborted
Onerror: called when an error occurs in the read operation
Onload: called when the read operation completes successfully
Onloadend: called when the read operation is complete, whether it succeeds or fails. The handler is called after onload or onerror
Onloadstart: called before the read operation is about to begin
Onprogress: called periodically during data reading
Under normal circumstances, when reading a file, the loadstart event is triggered first, and the readyState is 1 and the result is empty
Then, every time you pass a 50ms or so, a progress event is triggered, and the same information (properties) as the progress event of XHR can be obtained through the event object: lengthComputable, loaded, and total. In addition, although it may not contain all the data, the contents of the file can be read through the result property of FileReader in each progress event, and readyState is still 1.
When the file is read, the load event is triggered, and the readyState is 2. The result is the file content; if the error event occurs, the load event will not occur
/ * [loadstart] readyState:1;result: [progress] readyState:1;result:h4 {color: # F44336;} [load] readyState:2;result:h4 {color: # F44336;} [loadend] readyState:2;result:h4 {color: # F44336;} * / file1.onchange = function () {var reader = new FileReader (); reader.readAsText (file1.files [0]); reader.onloadstart = function (e) {console.log ('[loadstart] readyState:' + reader.readyState +') Result:' + reader.result);} reader.onload = function (e) {console.log ('[load] readyState:' + reader.readyState +'; result:' + reader.result);} reader.onloadend = function (e) {console.log ('[loadend] readyState:' + reader.readyState +'; result:' + reader.result) } reader.onprogress = function (e) {console.log ('[progress] readyState:' + reader.readyState +'; result:' + reader.result);}}
The error event is triggered when the file cannot be read for a variety of reasons. When the error event is triggered, the relevant information is saved to the error property of the FileReader. This property will hold an object that has only one property code, the error code. The error code is 1 for file not found, 2 for security error, 3 for read interrupt, 4 for file unreadable, 5 for coding error
Reader.onerror = function () {output [XSS _ clean] = "Could not read file, error code is" + reader.error.code;}
If you want to interrupt the reading process, you can call the abort () method, which triggers the abort event
After the load, error, or abort event is triggered, another event, loadend, is triggered. The occurrence of the loadend event means that the entire file has been read, or an error has occurred, or the reading process has been interrupted
Thumbnail image
Use the readAsDataURL () method of the FileReader object to read the file, and then filter out the picture through the type property of the File object
Select picture btn.onclick = function () {file1.click ();} file1.onchange = function () {var file = file1.files [0]; / / if a file is selected if (file) {/ / A picture is selected if (/ p_w_picpath/.test (file.type)) {var reader = new FileReader (); reader.readAsDataURL (file) Reader.onload = function () {uploadPreview.src = reader.result; msgName [XSS _ clean] = file.name;} / / other format files are selected} else {alert ("You must select a valid p_w_picpath file!");}
Blob URL
Using Blob URL, you can also display thumbnails
Select btn.onclick = function () {file1.click ();} / / Save the name of the picture var dataArr = []; file1.onchange = function () {var file = file1.files [0]; / / if a file is selected if (file) {var name = file.name; var id = name.split ('.'). Join ('_') / / check whether the picture has been stored in if (dataArr.indexOf (id) >-1) {/ / transfer the saved picture to the bottom fileList.appendChild (document.getElementById (id));} else {if (/ p_w_picpath/.test (file.type)) {dataArr.push (id) Var img = document.createElement ('img'); img.onload = function () {URL.revokeObjectURL (img.src);} img.src= URL.createObjectURL (file); img.height = 60; var oDiv = document.createElement (' div'); oDiv.id = id Var oSpan = document.createElement ('span'); oSpan[ XSS _ clean] = name + ":" + file.size + "bytes"; oDiv.appendChild (img); oDiv.appendChild (oSpan); fileList.appendChild (oDiv);}
File content
ReadAsText () can read and display the contents of the file as a string
Select the file btn.onclick = function () {file1.click ();} file1.onchange = function () {var file = file1.files [0]; / / if a file is selected if (file) {var reader = new FileReader (); reader.readAsText (file); reader.onload = function () {filedata [XSS _ clean] = reader.result;}
Drag and drop selection
Around reading file information, using HTML5 drag-and-drop API and file API can create an eye-catching user interface: after you create a custom drop target on the page, you can drag and drop files from the desktop to that target. Similar to dragging and dropping a picture or a link, dragging and dropping a file from the desktop into a browser also triggers the drop event. And the placed file can be read in event.dataTransfer.files, which is, of course, a File object, just like the File object obtained through the file input field
[note] IE9- browsers do not support event.dataTransfer
Select a picture file from the computer, drag and drop it to the specified area of the web page, and the picture thumbnail will be displayed on the web page.
Please drag and drop the picture file into the area function addEvent (target,type,handler) {if (target.addEventListener) {target.addEventListener (type,handler,false);} else {target.attachEvent ('on'+type,function (event) {return handler.call (target,event);});}} function preventDefault (e) {e = e | | event; if (e.preventDefault) {e.preventDefault () } else {e.returnValue = false;}} addEvent (document,'dragover',preventDefault); addEvent (document,'drop',preventDefault); addEvent (targetArea,'dragenter',preventDefault); addEvent (targetArea,'dragover',preventDefault); addEvent (targetArea,'dragleave',preventDefault); addEvent (targetArea,'drop',preventDefault); targetArea.ondragenter = function (e) {this.style.outline = "1px solid black";} targetArea.ondragleave = function (e) {this.style.outline = "" } targetArea.ondrop = function (e) {e = e | | event; this.style.outline = ""; var file = e.dataTransfer.files [0]; if (file) {/ / A picture is selected if (/ p_w_picpath/.test (file.type)) {var reader = new FileReader (); reader.readAsDataURL (file) Reader.onload = function () {var oDiv = document.createElement ('div'); oDiv.id = file.name.split ('.'). Join ('_') var img = new Image (); img.src = reader.result; img.height = 60; var oName = document.createElement ('span') OName [XSS _ clean] = file.name; var oDel = document.createElement ('button'); oDel [XSS _ clean] =' delete'; oDel.onclick = function () {result.removeChild (oDiv);} oDiv.appendChild (img) ODiv.appendChild (oName); oDiv.appendChild (oDel); result.appendChild (oDiv);} / / other format files are selected} else {alert ("You must select a valid p_w_picpath file!");}
File progress
File progress display can be achieved by using the loaded and total properties of the onprogress event
Select the file btn.onclick = function () {file1.click ();} file1.onchange = function () {var file = file1.files [0]; / / if a file is selected if (file) {var reader = new FileReader (); reader.readAsText (file); reader.onprogress = function (e) {e = e | | event Filedata [XSS _ clean] = 'file progress is:' + e.loaded +'/'+ e.total;}
File upload
Method 1: use form submission to upload files
The most basic way to upload a file is to use the HTML form to select a local file for upload, and to select a local file through tags in the form form. Also, you must set enctype to "multipart/form-data" and method to "post" in the element
In addition, you need to set an input box of type hidden in the form, where the name value is the hidden range of MAX_FILE_SIZE, and limit the size of the uploaded file by setting its value value
Upload files
Method 2: use FormData to upload files
Create a FormData () object through which you call the append () method and pass in the corresponding File object as a parameter. Then, pass the FormData object to the send () method of XHR
[note] IE9- browser does not support uploading files using FormData ()
Var oFile = document.getElementById ('file1'); oFile.onchange = function (e) {/ / create xhr object var xhr; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject (' Microsoft.XMLHTTP');}; var data = new FormData () Data.append ('file',oFile.files [0]) / / asynchronously accept the response xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {if (xhr.status = = 200) {/ / actual result [XSS _ clean] = xhr.responseText }} / / send request xhr.open ('post','pp.php',true); xhr.send (data);}
Method 3: use File API to upload files
Transfer binaries through File API
[note] IE9- browsers do not support
Var oFile = document.getElementById ('file1'); oFile.onchange = function (e) {/ / create xhr object var xhr; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject (' Microsoft.XMLHTTP');}; var data = oFile.files [0] / / asynchronously accept the response xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {if (xhr.status = = 200) {/ / actual result [XSS _ clean] = xhr.responseText;}} / / send the request xhr.open ('post','pp.php',true) Xhr.setRequestHeader ("content-type", data.type); xhr.send (data);}
Delete a file
Finally, a small knowledge point is mentioned and the value value of the control is left empty, but the second method is not supported by IE10- browsers.
Delete file method 1 delete file method 2var myFile = document.getElementById ('myFile'); var myForm = document.getElementById (' myForm'); btn1.onclick = function () {myFile.value =';} btn2.onclick = function () {myForm.reset ();}
Yes
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.