allway2 2022-06-24 07:23:25 阅读数:677
You can use JavaScript File API Load the contents of the selected file . This section describes File API The basic usage of .
Now let's see how to use File API.
stay HTML in , You can do this by input Elemental type Property is set to file To select the file .
<input type="file">
If you want to allow multiple file selections many Set up attribute .
<input type="file" multiple>
After the user selects the file change An event will occur .
To capture change events , First : change There is a way to write handlers directly in it . You can pass it on to onchange Handler to immediately access input elements in the handler , As shown below :
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>File Input Test</title>
<script>
function fileChanged(input) {
console.log(input);
for (let i = 0; i < input.files.length; i++) {
console.log(input.files[i]);
}
}
</script>
</head>
<body>
<input type="file" onchange="fileChanged(this)" multiple/>
</body>
</html>
You can also dynamically get input elements to handle change events .
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>File Input Test</title>
<script>
window.addEventListener('load', () => {
const f = document.getElementById('file1');
f.addEventListener('change', evt => {
const input = evt.target;
for (let i = 0; i < input.files.length; i++) {
console.log(input.files[i]);
}
});
});
</script>
</head>
<body>
<input type="file" id="file1" multiple/>
</body>
</html>
under these circumstances , The input element is passed to the target attribute of the event object .
When a change event occurs , The input element's files Property will pass a File object , This object represents the selected file .
If you display the file selection screen once and press the Cancel button without selecting a file , The change event handler... Will be called , But the file attribute will be a length of 0 Array of .
You can use File Object is stored somewhere and used later .
You can use FileReader Object to read File Object content . By way of File Object passed to FileReader Object to start reading .
There are several ways to read files .
FileReader Object read Blob Data in .File The object is also a Blob, Because it comes from Blob Derived .
When FileReader Object loading file , Would call onload event . Read results in FileReader Object's result Property .
Read text () After reading , The string is set in the result ,readAsArrayBuffer() After reading , The result will be set to ArrayBuffer object .
Now let's see how to actually read the file .
ad locum , We will make an example of the following behavior .
After selecting files , The contents of the selected file are displayed .
Displays the... Used in this operation check HTML Contents of files and stylesheets .
HTML The documents are as follows : Please save as file1.html.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>File API 1</title>
<script src="file1.js"></script>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<input type="file" id="file1" />
<pre id="pre1"></pre>
</body>
</html>
Input Element type attribute file As , As a ID file 1 Set .
Style sheets style .css as follows . I just changed the font slightly and added the background color , But I didn't do much .
@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap');
html {
font-family: 'Roboto', sans-serif;
}
pre {
font-family: 'Roboto mono', monospace;
font-size: 0.9rem;
background-color: #D6EAF8;
padding: 10px;
}
JavaScript file file1.js as follows .
window.addEventListener('load', () => {
const f = document.getElementById('file1');
f.addEventListener('change', evt => {
let input = evt.target;
if (input.files.length == 0) {
console.log('No file selected');
return;
}
const file = input.files[0];
const reader = new FileReader();
reader.onload = () => {
const pre = document.getElementById('pre1');
pre.innerHTML = reader.result;
};
reader.readAsText(file);
});
});
In the load event handler of the window object , Set the change event handler for the input element of the file .
When you select a file , This invokes the change event handler .
One Event Object is passed to the event handler . The input element that performs the file selection operation is passed to the target attribute of the event object . This Input elements file This attribute is set to the list of selected file objects .
We're not here this time input Set... On the element multiple attribute , So only one will be set File object .
Get File After the object , The next step is to read the file .
const file = input.files[0];
const reader = new FileReader();
reader.onload = () => {
const pre = document.getElementById('pre1');
pre.innerHTML = reader.result;
};
reader.readAsText(file);
such , pre The contents of the file are set in the element .
ok , In the code above File reader Object's Read text () Before calling a method load I have set up an event handler .
File reader There are more events available , But each time you set them up and then call them, it can be a bit complicated .
So let's use Promises To organize our code .
Prepare a receiving File Object function object , Such as :
const readAsTextReader = file => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onloadstart = ev => {
console.log(`onloadstart: total=${ev.loaded}/${ev.loaded}`);
};
reader.onloadend = ev => {
console.log(`onloadend: total=${ev.loaded}/${ev.loaded}`);
};
reader.onprogress = ev => {
console.log(`onprogress: total=${ev.loaded}/${ev.loaded}`);
};
reader.onerror = () => {
reader.abort();
reject('Unknown error occurred during reading the file');
};
reader.onload = () => {
console.log('onload');
resolve(reader.result);
};
reader.readAsText(file);
});
};
such , Asynchronous processing when reading files uses Promise Of then and catch, The application is as follows .
window.addEventListener('load', () => {
const f = document.getElementById('file1');
f.addEventListener('change', evt => {
const input = evt.target;
if (input.files.length == 0) {
return;
}
const file = input.files[0];
console.log(file);
readAsTextReader(file)
.then(value => {
const pre = document.getElementById('pre1');
pre.innerHTML = value;
})
.catch(reason => {
alert(reason);
});
});
});
Next , Let's create a simple binary viewer as an example , Not only can you read text files , You can also read binary files .
Select the file and use FileReader The location of the read file is the same .
However , This time, readAsArrayBuffer() Read the file . As a result ArrayBuffer return .
ArrayBuffer yes JavaScript Byte string in . For more information , see also “ Use ArrayBuffer Processing binary data ”.
const readAsArrayBufferReader = file => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onerror = () => {
reader.abort();
reject('Unknown error occurred during reading the file');
};
reader.onload = () => {
console.log('onload');
resolve(reader.result);
};
reader.readAsArrayBuffer(file);
});
};
window.addEventListener('load', () => {
const f = document.getElementById('file1');
f.addEventListener('change', evt => {
const input = evt.target;
if (input.files.length == 0) {
return;
}
let file = input.files[0];
console.log(file);
if (!file) {
return;
}
if (file.size > 50 * 1024) {
alert('Please select a file smaller than 50kb.');
return;
}
readAsArrayBufferReader(file)
.then(buff => {
console.log(buff);
let s = '';
let a = new Uint8Array(buff);
for (let i = 0; i * 16 < a.length; i++) {
let line = '';
let p = i * 16;
let b = a.slice(p, Math.min(a.length, p + 16));
for (const e of b) {
let h = e
.toString(16)
.toUpperCase()
.padStart(2, '0');
line += ' ' + h;
}
let addr = p
.toString(16)
.toUpperCase()
.padStart(8, '0');
line = `${addr}:${line}\n`;
s += line;
}
let pre = document.getElementById('pre1');
pre.innerHTML = s;
})
.catch(reason => {
alert(reason);
});
});
});
This time the file size is limited to 50KB.
Read from as ArrayBuffer Create a..., based on your data Uint8Array object . From there, slice () Format as 16 Bytes are displayed in increments .
up to now , We have introduced how to do it in JavaScript Use in File Objects and FileReader Read the file , How to use Promise Simplify asynchronous processing , And examples of processing binary data .
copyright:author[allway2],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240117229942.html