javascript - 用 JS 读取本地 XML

标签 javascript json xml

目前,由于 security policy Chromium如果没有 --allow-file-access-from-files,则无法通过 ajax 读取本地文件。但是我目前需要创建一个 web 应用程序,其中数据库是一个 xml 文件(在极端情况下是 json),位于一个带有 index.html 的目录中。据了解,用户可以在本地运行这个应用程序。是否有读取 xml- (json-) 文件而不将其包装在函数中并更改为 js 扩展名的解决方法?

loadXMLFile('./file.xml').then(xml => {
    // working with xml
});

function loadXMLFile(filename) {
    return new Promise(function(resolve, reject) {
        if('ActiveXObject' in window) {
            // If is IE
            var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
            xmlDoc.async = false;
            xmlDoc.load(filename);

            resolve(xmlDoc.xml);
        } else {
            /*
             * how to read xml file if is not IE?
             * ...
             * resolve(something);
             */
        }

    }
}

最佳答案

正在访问 file:使用 XMLHttpRequest() 的 Chromium 协议(protocol)或 <link>没有 --allow-file-access-from-files 的元素默认情况下不启用在 chromium 实例启动时设置的标志。

--allow-file-access-from-files

By default, file:// URIs cannot read other file:// URIs. This is an override for developers who need the old behavior for testing.


At the moment, due to the security policy Chromium can not read local files via ajax without --allow-file-access-from-files. But I currently need to create a web application where the database is a xml-file (in the extreme case, json), located in one dir with index.html. It is understood that the user can run this application locally. Are there workarounds for reading xml- (json-) file, without wrapping it in a function and change to js extension?

如果用户知道应用程序将使用本地文件,您可以使用 <input type="file">用户从用户本地文件系统上传文件的元素,使用 FileReader 处理文件,然后继续申请。

否则,建议用户使用应用程序需要使用 --allow-file-access-from-files 启动 Chrome 标志集,这可以通过为此目的创建一个启动器来完成,为 chromium 实例指定一个不同的用户数据目录。例如,启动器可以是

/usr/bin/chromium-browser --user-data-dir="/home/user/.config/chromium-temp" --allow-file-access-from-files

另见 How do I make the Google Chrome flag “--allow-file-access-from-files” permanent?

上述命令也可以在 terminal 运行

$ /usr/bin/chromium-browser --user-data-dir="/home/user/.config/chromium-temp" --allow-file-access-from-files

无需创建桌面启动器;当 chromium 实例关闭时在哪里运行

$ rm -rf /home/user/.config/chromium-temp

删除 chromium 实例的配置文件夹。

设置标志后,用户可以包含 <link>带有 rel="import" 的元素属性和 href指向本地文件和type设置为 "application/xml" , 对于 XMLHttpRequest 以外的选项获取文件。访问XML document使用

const doc = document.querySelector("link[rel=import]").import;

参见 Is there a way to know if a link/script is still pending or has it failed .


另一种替代方案,虽然涉及更多,但会使用 requestFileSystem将文件存储在 LocalFileSystem .

或者创建或修改 chrome 应用程序并使用

chrome.fileSystem

参见 GoogleChrome/chrome-app-samples/filesystem-access .


最简单的方法是提供一种通过肯定的用户操作上传文件的方法;处理上传的文件,然后继续申请。

const reader = new FileReader;

const parser = new DOMParser;

const startApp = function startApp(xml) {
  return Promise.resolve(xml || doc)
};

const fileUpload = document.getElementById("fileupload");

const label = document.querySelector("label[for=fileupload]");

const handleAppStart = function handleStartApp(xml) {
  console.log("xml document:", xml);
  label.innerHTML = currentFileName + " successfully uploaded";
  // do app stuff
}

const handleError = function handleError(err) {
  console.error(err)
}

let doc;
let currentFileName;

reader.addEventListener("loadend", handleFileRead);

reader.addEventListener("error", handleError);

function handleFileRead(event) {
  label.innerHTML = "";
  currentFileName = "";
  try {
    doc = parser.parseFromString(reader.result, "application/xml");
    fileUpload.value = "";

    startApp(doc)
    .then(function(data) {
        handleAppStart(data)
    })
    .catch(handleError);
  } catch (e) {
    handleError(e);
  }
}

function handleFileUpload(event) {
  let file = fileUpload.files[0];
  if (/xml/.test(file.type)) {
    reader.readAsText(file);
    currentFileName = file.name;
  }
}

fileUpload.addEventListener("change", handleFileUpload)
<input type="file" name="fileupload" id="fileupload" accept=".xml" />
<label for="fileupload"></label>

关于javascript - 用 JS 读取本地 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41279589/

相关文章:

javascript - 在带有扩展的 map 中使用 Promise

sql - 使用 SQL Server 2005 XML API 规范化 XML 片段

android - 安卓:elevation tag raises issue in android layout file

javascript - 按钮上的 Jquery Mobile

javascript - 处理获取响应的正确方法是什么

python - 使用 Flask 和 gunicorn 进行 JSON 格式的日志记录

json - Scalaz 树到 JSON

javascript - 如何处理外部 api JSON 而不是 JSONP

xml - 如何使用xsl 2.0函数

javascript - Shinydashboard:Google 地点自动完成。 InvalidValueError:不是 HTMLInputElement 的实例