【发布时间】:2014-10-04 11:00:41
【问题描述】:
是否可以在文件系统/网络驱动器(c:\abc.xlsx 或 p:\abc.xlsx)上打开本地文件?
如果是这样,是否可以通过我为谷歌浏览器创建的自定义扩展来做到这一点?
【问题讨论】:
是否可以在文件系统/网络驱动器(c:\abc.xlsx 或 p:\abc.xlsx)上打开本地文件?
如果是这样,是否可以通过我为谷歌浏览器创建的自定义扩展来做到这一点?
【问题讨论】:
HTML5 最终通过文件 API 规范提供了一种与本地文件交互的标准方式。
规范提供了几个用于从“本地”文件系统访问文件的接口:
当与上述数据结构结合使用时,FileReader 接口可用于通过熟悉的 JavaScript 事件处理异步读取文件。因此,可以监视读取的进度、捕获错误并确定加载何时完成。在许多方面,API 类似于 XMLHttpRequest 的事件模型。
首先要做的是检查您的浏览器是否完全支持 File API:
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
接下来,处理文件选择:
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
要读取文件,请像这样扩展 handleFileSelect:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
最后,这是文件规范:http://www.w3.org/TR/file-upload/
【讨论】:
可以通过设置--allow-file-access-from-files标志来完成。
不是正常打开Chrome,而是运行:
path\to\your\chrome\installation\chrome.exe --allow-file-access-from-files
【讨论】: