Javascript 读取外部的本地json文件
方案1
运行本地web服务器,提供文件服务
方案2
1.data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]'; (json文件内部代码)
1.<script type="text/javascript" src="data.json"></script>
2.var mydata = JSON.parse(data); 方案3
1.function readTextFile(file, callback) {
2. var rawFile = new XMLHttpRequest();
3. rawFile.overrideMimeType("application/json");
4. rawFile.open("GET", file, true);
5. rawFile.onreadystatechange = function() {
6. if (rawFile.readyState === 4 && rawFile.status == "200") {
7. callback(rawFile.responseText);
8. }
9. }
10. rawFile.send(null);
11.}
12.
13.//usage:
14.readTextFile("/Users/Documents/workspace/test.json", function(text){
15. var data = JSON.parse(text);
16. console.log(data);
17.});
另外,这个功能还可以用于加载.html或.txt文件,将mime类型参数覆盖到"text/html","text/plain"等。
方案4
使用FileAPI
1.// 检查文件API的支持
2.if (window.File && window.FileReader && window.FileList && window.Blob) {
3. // 支持.
4.} else {
5. alert('这个浏览器不完全支持文件API');
6.}
选择文件
1.使用表单输入进行选择文件
1.<input type="file" id="files" name="files[]" multiple />
2.<output id="list"></output> 1.<script>
2. function handleFileSelect(evt) {
3. var files = evt.target.files; // FileList object
4. // files is a FileList of File objects. List some properties.
5. var output = [];
6. for (var i = 0, f; f = files[i]; i++) {
7. output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
8. f.size, ' bytes, last modified: ',
9. f.lastModifiedDate.toLocaleDateString(), '</li>');
10. }
11. document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
12. }
13. document.getElementById('files').addEventListener('change', handleFileSelect, false);
14.</script>
2.使用拖放进行选择文件
1.<div id="drop_zone">Drop files here</div>
2.<output id="list"></output> 1.<script>
2. function handleFileSelect(evt) {
3. evt.stopPropagation();
4. evt.preventDefault();
5. var files = evt.dataTransfer.files; // FileList object.
6. // files is a FileList of File objects. List some properties.
7. var output = [];
8. for (var i = 0, f; f = files[i]; i++) {
9. output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
10. f.size, ' bytes, last modified: ',
11. f.lastModifiedDate.toLocaleDateString(), '</li>');
12. }
13. document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
14. }
15. function handleDragOver(evt) {
16. evt.stopPropagation();
17. evt.preventDefault();
18. evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
19. }
20. // Setup the dnd listeners.
21. var dropZone = document.getElementById('drop_zone');
22. dropZone.addEventListener('dragover', handleDragOver, false);
23. dropZone.addEventListener('drop', handleFileSelect, false);
24.</script>
读取文件
获得文件后,使用FileReader对象读取文件到内存.读取完成后,将触发onload事件,result属性用于访问文件的数据,
FileReader包括四个异步读取文件的选项.
1.FileReader.readAsBinaryString(Blob|File) - result 属性将包含二进制字符串形式的 file/blob 数据。每个字节均由一个 [0..255] 范围内的整数表示。
2.FileReader.readAsText(Blob|File, opt_encoding) - result 属性将包含文本字符串形式的 file/blob 数据。该字符串在默认情况下采用“UTF-8”编码。使用可选编码参数可指定其他格式。
3.FileReader.readAsDataURL(Blob|File) - result 属性将包含编码为数据网址的 file/blob 数据。
4.FileReader.readAsArrayBuffer(Blob|File) - result 属性将包含 ArrayBuffer 对象形式的 file/blob 数 1.对您的 FileReader 对象调用其中某一种读取方法后,可使用 onloadstart、onprogress、onload、onabort、onerror 和 onloadend 跟踪其进度。
读取文件呈现缩略图(例子)
1.<style>
2. .thumb {
3. height: 75px;
4. border: 1px solid #000;
5. margin: 10px 5px 0 0;
6. }
7.</style>
8.
9.<input type="file" id="files" name="files[]" multiple />
10.<output id="list"></output>
11.
12.<script>
13. function handleFileSelect(evt) {
14. var files = evt.target.files; // FileList object
15.
16. // Loop through the FileList and render image files as thumbnails.
17. for (var i = 0, f; f = files[i]; i++) {
18.
19. // Only process image files.
20. if (!f.type.match('image.*')) {
21. continue;
22. }
23.
24. var reader = new FileReader();
25.
26. // Closure to capture the file information.
27. reader.onload = (function(theFile) {
28. return function(e) {
29. // Render thumbnail.
30. var span = document.createElement('span');
31. span.innerHTML = ['<img class="thumb" src="', e.target.result,
32. '" title="', escape(theFile.name), '"/>'].join('');
33. document.getElementById('list').insertBefore(span, null);
34. };
35. })(f);
36.
37. // Read in the image file as a data URL.
38. reader.readAsDataURL(f);
39. }
40. }
41.
42. document.getElementById('files').addEventListener('change', handleFileSelect, false);
43.</script>
分割文件
1.if (file.webkitSlice) { //关键代码
2. var blob = file.webkitSlice(startingByte, endindByte);
3.} else if (file.mozSlice) {
4. var blob = file.mozSlice(startingByte, endindByte);
5.}
6.reader.readAsBinaryString(blob);
如何读取文件块(例子)
1.<style>
2. #byte_content {
3. margin: 5px 0;
4. max-height: 100px;
5. overflow-y: auto;
6. overflow-x: hidden;
7. }
8. #byte_range { margin-top: 5px; }
9.</style>
10.
11.<input type="file" id="files" name="file" /> Read bytes:
12.<span class="readBytesButtons">
13. <button data-startbyte="0" data-endbyte="4">1-5</button>
14. <button data-startbyte="5" data-endbyte="14">6-15</button>
15. <button data-startbyte="6" data-endbyte="7">7-8</button>
16. <button>entire file</button>
17.</span>
18.<div id="byte_range"></div>
19.<div id="byte_content"></div>
20.
21.<script>
22. function readBlob(opt_startByte, opt_stopByte) {
23.
24. var files = document.getElementById('files').files;
25. if (!files.length) {
26. alert('Please select a file!');
27. return;
28. }
29.
30. var file = files[0];
31. var start = parseInt(opt_startByte) || 0;
32. var stop = parseInt(opt_stopByte) || file.size - 1;
33.
34. var reader = new FileReader();
35.
36. // If we use onloadend, we need to check the readyState.
37. reader.onloadend = function(evt) {
38. if (evt.target.readyState == FileReader.DONE) { // DONE == 2
39. document.getElementById('byte_content').textContent = evt.target.result;
40. document.getElementById('byte_range').textContent =
41. ['Read bytes: ', start + 1, ' - ', stop + 1,
42. ' of ', file.size, ' byte file'].join('');
43. }
44. };
45.
46. if (file.webkitSlice) {
47. var blob = file.webkitSlice(start, stop + 1);
48. } else if (file.mozSlice) {
49. var blob = file.mozSlice(start, stop + 1);
50. }
51. reader.readAsBinaryString(blob);
52. }
53.
54. document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
55. if (evt.target.tagName.toLowerCase() == 'button') {
56. var startByte = evt.target.getAttribute('data-startbyte');
57. var endByte = evt.target.getAttribute('data-endbyte');
58. readBlob(startByte, endByte);
59. }
60. }, false);
61.</script>
监控读取进度
1.onloadstart 和 onprogress 事件可用于监控读取进度
通过显示进度条来监控读取状态(例子)
1.<style>
2. #progress_bar {
3. margin: 10px 0;
4. padding: 3px;
5. border: 1px solid #000;
6. font-size: 14px;
7. clear: both;
8. opacity: 0;
9. -moz-transition: opacity 1s linear;
10. -o-transition: opacity 1s linear;
11. -webkit-transition: opacity 1s linear;
12. }
13. #progress_bar.loading {
14. opacity: 1.0;
15. }
16. #progress_bar .percent {
17. background-color: #99ccff;
18. height: auto;
19. width: 0;
20. }
21.</style>
22.
23.<input type="file" id="files" name="file" />
24.<button onclick="abortRead();">Cancel read</button>
25.<div id="progress_bar"><div class="percent">0%</div></div>
26.
27.<script>
28. var reader;
29. var progress = document.querySelector('.percent');
30.
31. function abortRead() {
32. reader.abort();
33. }
34.
35. function errorHandler(evt) {
36. switch(evt.target.error.code) {
37. case evt.target.error.NOT_FOUND_ERR:
38. alert('File Not Found!');
39. break;
40. case evt.target.error.NOT_READABLE_ERR:
41. alert('File is not readable');
42. break;
43. case evt.target.error.ABORT_ERR:
44. break; // noop
45. default:
46. alert('An error occurred reading this file.');
47. };
48. }
49.
50. function updateProgress(evt) {
51. // evt is an ProgressEvent.
52. if (evt.lengthComputable) {
53. var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
54. // Increase the progress bar length.
55. if (percentLoaded < 100) {
56. progress.style.width = percentLoaded + '%';
57. progress.textContent = percentLoaded + '%';
58. }
59. }
60. }
61.
62. function handleFileSelect(evt) {
63. // Reset progress indicator on new file selection.
64. progress.style.width = '0%';
65. progress.textContent = '0%';
66.
67. reader = new FileReader();
68. reader.onerror = errorHandler;
69. reader.onprogress = updateProgress;
70. reader.onabort = function(e) {
71. alert('File read cancelled');
72. };
73. reader.onloadstart = function(e) {
74. document.getElementById('progress_bar').className = 'loading';
75. };
76. reader.onload = function(e) {
77. // Ensure that the progress bar displays 100% at the end.
78. progress.style.width = '100%';
79. progress.textContent = '100%';
80. setTimeout("document.getElementById('progress_bar').className='';", 2000);
81. }
82.
83. // Read in the image file as a binary string.
84. reader.readAsBinaryString(evt.target.files[0]);
85. }
86.
87. document.getElementById('files').addEventListener('change', handleFileSelect, false);
88.</script>
出处1.https://www.html5rocks.com/zh/tutorials/file/dndfiles/
出处2.https://vimsky.com/article/3575.html
-- https://www.cnblogs.com/streamwang/p/8056301.html
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var reader = new FileReader();//这是核心,读取操作就是由它完成.
reader.readAsText(new Blob(files));//读取文件的内容,也可以读取文件的URL
reader.onload = function () {
//当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
console.log(this.result);
} //usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});