3 回答
TA贡献2003条经验 获得超2个赞
编辑以添加有关文件API的信息
FileReaderFile
var file = document.getElementById("fileForUpload").files[0];if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
document.getElementById("fileContents").innerHTML = evt.target.result;
}
reader.onerror = function (evt) {
document.getElementById("fileContents").innerHTML = "error reading file";
}}原始答案
fileNamefileSize
TA贡献1801条经验 获得超8个赞
<input type="file">
function onFileLoad(elementId, event) {
document.getElementById(elementId).innerText = event.target.result;
}
function onChooseFile(event, onLoadFileHandler) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
let input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
let file = input.files[0];
let fr = new FileReader();
fr.onload = onLoadFileHandler;
fr.readAsText(file);
}
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />
<p id="contents"></p>
TA贡献1836条经验 获得超5个赞
var CallBackFunction = function(content){
alert(content);}ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chromefunction ReadFileAllBrowsers(FileElement, CallBackFunction){try{
var file = FileElement.files[0];
var contents_ = "";
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(evt)
{
CallBackFunction(evt.target.result);
}
reader.onerror = function (evt) {
alert("Error reading file");
}
}}catch (Exception)
{
var fall_back = ieReadFile(FileElement.value);
if(fall_back != false)
{
CallBackFunction(fall_back);
}
}}///Reading files with Internet Explorerfunction ieReadFile(filename){
try
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
}
catch (Exception)
{
alert(Exception);
return false;
}
}添加回答
举报
