FileReader和CodeMirror加载文件复杂性

时间:2013-07-15 03:58:17

标签: javascript api filereader codemirror

带预览的默认CodeMirror HTML编辑器 - http://jsfiddle.net/D9MvH/1/ - http://liveweave.com/zSqCfA

使用FileReader API在CodeMirror中加载文件 - http://liveweave.com/VvsXN9

这是我正在尝试做的一个非常简单的例子。 (保存功能不适用于这些在线编辑器,但导入文件功能适用于这个简单的编辑器) - http://liveweave.com/MrUBfZ

我的问题是当我单击输入文件表单以浏览文件时。我选择要打开的HTML文档,它不会在CodeMirror中用/打开。我尝试了所有我的知识,无法让它发挥作用。任何人都可以帮忙吗?

HTML

<input type="file" onchange="loadfile(this)">

的JavaScript

var delay;

// Initialize CodeMirror editor
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
    mode: 'text/html',
    tabMode: 'indent',
    lineNumbers: true,
    lineWrapping: true,
    autoCloseTags: true
});

// Live preview
editor.on("change", function() {
    clearTimeout(delay);
    delay = setTimeout(updatePreview, 300);
});

function updatePreview() {
    var previewFrame = document.getElementById('preview');
    var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
    preview.open();
    preview.write(editor.getValue());
    preview.close();
}
setTimeout(updatePreview, 300);

function saveTextAsFile() {
    var textToWrite = document.getElementById("code").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "myfile.html";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);}

function loadfile(input){
    var reader = new FileReader()
    reader.onload = function(e) {
        editor.setValue = e.target.result;}
    reader.readAsText(input.files[0]);}

    var input = document.getElementById("select");

    function selectTheme() {
      var theme = input.options[input.selectedIndex].innerHTML;
      editor.setOption("theme", theme);
    }

    var choice = document.location.search &&
               decodeURIComponent(document.location.search.slice(1));
    if (choice) {
      input.value = choice;
      editor.setOption("theme", choice);
    }

完整代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: HTML5 preview</title>
<script src='http://codemirror.net/lib/codemirror.js'></script>
<script src='http://codemirror.net/mode/xml/xml.js'></script>
<script src='http://codemirror.net/mode/javascript/javascript.js'></script>
<script src='http://codemirror.net/mode/css/css.js'></script>
<script src='http://codemirror.net/mode/htmlmixed/htmlmixed.js'></script>
<link rel='stylesheet' href='http://codemirror.net/lib/codemirror.css'>
<link rel='stylesheet' href='http://codemirror.net/doc/docs.css'>
<style type='text/css'>
.CodeMirror {
    float: left;
    width: 50%;
    border: 1px solid black;}

iframe {
    width: 49%;
    float: left;
    height: 300px;
    border: 1px solid black;
    border-left: 0px;}
</style>
</head>
<body>
    <textarea id="code" name="code"><!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>HTML5 canvas demo</title>
<style>p {font-family: monospace;}</style>
</head>
<body>
    <p>Canvas pane goes here:</p>
    <canvas id=pane width=300 height=200></canvas>

    <script>
      var canvas = document.getElementById('pane');
      var context = canvas.getContext('2d');

      context.fillStyle = 'rgb(250,0,0)';
      context.fillRect(10, 10, 55, 50);

      context.fillStyle = 'rgba(0, 0, 250, 0.5)';
      context.fillRect(30, 30, 55, 50);
    </script>
</body>
</html></textarea>

    <iframe id="preview"></iframe>

    <input type="file" onchange="loadfile(this)">
    <a href="#my-header" onclick='saveTextAsFile()'>Save/Download</a>

<script>
var delay;

// Initialize CodeMirror editor
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
    mode: 'text/html',
    tabMode: 'indent',
    lineNumbers: true,
    lineWrapping: true,
    autoCloseTags: true
});

// Live preview
editor.on("change", function() {
    clearTimeout(delay);
    delay = setTimeout(updatePreview, 300);
});

function updatePreview() {
    var previewFrame = document.getElementById('preview');
    var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
    preview.open();
    preview.write(editor.getValue());
    preview.close();
}
setTimeout(updatePreview, 300);

function saveTextAsFile() {
    var textToWrite = document.getElementById("code").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "myfile.html";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);}

function loadfile(input){
    var reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('code').value = e.target.result;}
    reader.readAsText(input.files[0]);}

    var input = document.getElementById("select");

    function selectTheme() {
      var theme = input.options[input.selectedIndex].innerHTML;
      editor.setOption("theme", theme);
    }

    var choice = document.location.search &&
               decodeURIComponent(document.location.search.slice(1));
    if (choice) {
      input.value = choice;
      editor.setOption("theme", choice);
    }
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

你只是误用了CodeMirror;当文件内容加载到阅读器中时,而不是将value分配给 textarea元素,例如:

reader.onload = function(e) {
    document.getElementById('code').value = e.target.result;
}

...使用CodeMirror API并通过编辑器实例 setValue()方法插入内容,如下所示:

reader.onload = function(e) {
    editor.setValue(e.target.result);
}

请参阅CodeMirror docs for doc.setValue(content: string),此处是updated, working demo说明这一点。

答案 1 :(得分:0)

这是示例示例。

<script src="codemirror/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror/lib/codemirror.css"/>
<script src="codemirror/mode/clike/clike1.js"></script>
<script src="codemirror/mode/javascript/javascript.js"></script>

<div id="editor"> </div>
<div>
    <input type="file" onchange="localLoad(this.files);" />
</div>

<script>
   var myCodeMirror = CodeMirror(
   document.getElementById('editor'), {
      lineNumbers: true
   });

   function localLoad(files) {
       if (files.length == 1) {
            document.title = escape(files[0].name);
            var reader = new FileReader();
            reader.onload = function(e) {
              myCodeMirror.setValue(e.target.result);
            };
            reader.readAsText(files[0]);
         }
    }
</script>

以上操作已完成div。如果您想要文本区域,请进行以下更改:

<textarea id="editor" name="field1"></textarea>

 <script>
 var myCodeMirror = CodeMirror.fromTextArea
  document.getElementById('editor'),{
  lineNumbers: true
   });
   myCodeMirror.setSize(null, 600);
 </script>