Редактор Alloyui Ace для чтения и записи файла

Как читать и писать файл html или php с помощью редактора ace (Alloui), в примере я просто получаю значение для редактирования не из файла, и я сделал это, чтобы просмотреть документацию, но не понял, как читать и писать код из файла.

пример

YUI().use(
  'aui-ace-editor',
  function(Y) {
    var editor = new Y.AceEditor(
      {
        boundingBox: '#myEditor',
        height: '200',
        mode: 'javascript',
        value: 'alert("Write something here...");',
        width: '700'
      }
    ).render();

    var mode = Y.one('#mode');

    if (mode) {
      var contents = {
        javascript: 'alert("Write something here...");',
        json: '{"value": "Write something here..."}',
        php: '<?php echo "Write something here..."; ?>',
        xml: '<value attr="something">Write something here...</value>'
      };

      var currentMode = 'javascript';

      var updateValue = function() {
        editor.set('value', contents[currentMode]);
      };

      mode.on(
        'change',
        function(event) {
          currentMode = this.val();
          editor.set('mode', currentMode);
          updateValue();
        }
      );
    }
  }
);

как вызвать код файла? или это можно сделать, только изменив путь/URL файла value: 'alert("Write something here...");'whit?

Спасибо


person Riski Febriansyah    schedule 22.05.2017    source источник


Ответы (1)


Вы не можете записывать или читать системные файлы с помощью JavaScript. Однако вы можете писать в файлы с помощью чтение содержимого загруженных файлов и загрузка их в AceEditor. Используйте <input type="file" />, чтобы разрешить пользователю загружать файл. После загрузки файла установите value AceEditor в качестве содержимого файла.

AUI().use('aui-ace-editor', function(A) {
  var aceEditor;
  var fileInput = A.one('#fileInput');
  fileInput.on('change', function(event) {
    var file = fileInput.getDOMNode().files[0];

    if (file) {

      // Other types may also be appropriate here:
      if (file.type.startsWith('text/') || file.type.startsWith('application/')) {
        var reader = new FileReader();

        reader.onload = function (onloadEvent) {

            if (!aceEditor) {
             aceEditor = new A.AceEditor({
                /* ...your AceEditor config... */
                mode: 'text',
                render: true
              });
            }

            aceEditor.set('value', onloadEvent.target.result);
        }

        reader.onerror = function (onerrorEvent) {
            alert('File could not be read. Aborting.')
        }

        reader.readAsText(file, "UTF-8");
      }
      else {
        alert('File does not contain text. Aborting.');
      }
    }
  });
});

Вы также можете попытаться угадать mode, который должен использовать редактор, по типу MIME файла:

aceEditor.set('mode', file.type.replace(/^(text|application)\/(x-)?/, ''));

Чтобы загрузить отредактированный файл, вы можете использовать URI данных:

var downloadFileButton = Y.one('#downloadFileButton');
downloadFileButton.on('click', function(clickEvent) {
  var downloadFileLink = Y.Node.create('<a href="data:' +
    fileType + ';charset=utf-8,' +
    encodeURIComponent(aceEditor.get('value')) +
    '" download="' + fileName + '" style="display: none;" />');
  var bodyElement = Y.one('body');
  bodyElement.appendChild(downloadFileLink);
  downloadFileLink.getDOMNode().click();
  bodyElement.removeChild(downloadFileLink);
});

Вот работающий пример со всеми вышеперечисленными функциями/кодом:

YUI().use('aui-ace-editor', function(Y) {
  var aceEditor;
  var fileName;
  var fileType;
  var fileInput = Y.one('#fileInput');
  fileInput.on('change', function(event) {
    var file = fileInput.getDOMNode().files[0];

    if (file) {

      fileType = file.type;

      // Other types may also be appropriate here:
      if (fileType.startsWith('text/') || fileType.startsWith('application/')) {
        fileName = file.name;
        var reader = new FileReader();

        reader.onload = function (onloadEvent) {

            if (!aceEditor) {
             aceEditor = new Y.AceEditor({
                boundingBox: '#aceEditor',
                mode: 'text',
                value: 'Upload a file to begin editing.',
                height: '200',
                width: '700',
                render: true
              });
              var downloadFileButton = Y.one('#downloadFileButton');
              downloadFileButton.setStyle('display', null);
              downloadFileButton.on('click', function(clickEvent) {
                var downloadFileLink = Y.Node.create('<a href="data:' +
                  fileType + ';charset=utf-8,' +
                  encodeURIComponent(aceEditor.get('value')) +
                  '" download="' + fileName + '" style="display: none;" />');
                var bodyElement = Y.one('body');
                bodyElement.appendChild(downloadFileLink);
                downloadFileLink.getDOMNode().click();
                bodyElement.removeChild(downloadFileLink);
              });
            }

            aceEditor.set('value', onloadEvent.target.result);
            aceEditor.set('mode', fileType.replace(/^(text|application)\/(x-)?/, ''));
        }

        reader.onerror = function (onerrorEvent) {
            alert('File could not be read. Aborting.')
        }

        reader.readAsText(file, "UTF-8");
      }
      else {
        alert('File does not contain text. Aborting.');
      }
    }
  });
});
<script src="https://cdn.rawgit.com/stiemannkj1/701826667a70997013605edcd37e92a6/raw/469fe1ae297e72a5a80eb9015003b7b04eac735e/alloy-ui-3.0.1_aui_aui-min.js"></script>
<link href="https://cdn.rawgit.com/stiemannkj1/90be22de7f48c729b443af14796d91d3/raw/a9f35ceedfac7fc0559b121bed105eaf80f10bf2/aui-css_css_bootstrap.min.css" rel="stylesheet"></link>
<div class="yui3-skin-sam">
  <input type="file" id="fileInput">
  <div id="aceEditor"></div>
  <button id="downloadFileButton" style="display: none;">Download File</button>
</div>

person stiemannkj1    schedule 31.05.2017