用 JS 读取本地 XML [英] Read local XML with JS

查看:33
本文介绍了用 JS 读取本地 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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);
             */
        }

    }
}

推荐答案

Accessing file: 协议在 Chromium 使用 XMLHttpRequest()<在 Chromium 实例启动时没有设置 --allow-file-access-from-files 标志的/code> 元素默认不启用.

Accessing file: protocol at chromium using XMLHttpRequest() or <link> element without --allow-file-access-from-files flag set at chromium instance launch is not enabled by default.

--allow-file-access-from-files

默认情况下,file://URI 无法读取其他 file://URI.这是一为需要旧行为进行测试的开发者覆盖.

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

目前,由于安全策略 Chromium 无法读取本地通过没有 --allow-file-access-from-files 的 ajax 访问文件.但是我当前需要创建一个 Web 应用程序,其中数据库是一个xml 文件(在极端情况下为 json),位于一个目录中索引.html.据了解,用户可以运行此应用程序当地.是否有读取 xml- (json-) 文件的解决方法,而不需要将其包装在一个函数中并更改为 js 扩展名?

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,然后继续申请.

If user is aware that local files are to be used by the application you can utilize <input type="file"> element for user to upload file from user local filesystem, process file using FileReader, then proceed with application.

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

Else, advise user that use of application requires launching chromium with --allow-file-access-from-files flag set, which can be done by creating a launcher for this purpose, specifying a different user data directory for the instance of chromium. The launcher could be, for example

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

另见 如何使 Google Chrome 标记--allow-file-access-from-files"永久化?

上面的命令也可以在terminal

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

无需创建桌面启动器;当铬的实例关闭时运行

without creating a desktop launcher; where when the instance of chromium is closed run

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

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

to remove the configuration folder for the instance of chromium.

一旦设置了标志,用户就可以包含带有 rel="import" 属性和 href 指向本地的 元素file 和 type 设置为 "application/xml",用于除 XMLHttpRequest 之外的选项来获取文件.使用

Once the flag is set, user can include <link> element with rel="import" attribute and href pointing to local file and type set to "application/xml", for option other than XMLHttpRequest to get file. Access XML document using

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

有没有办法知道链接/脚本是否仍在等待或失败.

另一种替代方案,虽然更复杂,但使用 requestFileSystem 将文件存储在 LocalFileSystem.

Another alternative, though more involved, would be to use requestFileSystem to to store the file at LocalFileSystem.

或创建或修改 Chrome 应用程序并使用

Or create or modify a chrome app and use

chrome.fileSystem

参见 GoogleChrome/chrome-app-samples/文件系统访问.

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

The simplest approach would be to provide a means for file upload by affirmative user action; process the uploaded file, then proceed with the application.

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>

这篇关于用 JS 读取本地 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆