【问题标题】:Loading file from local directory?从本地目录加载文件?
【发布时间】:2013-09-19 06:30:51
【问题描述】:

我正在使用 ajax 调用将数据加载到我的应用程序中。它适用于这样的路径

../../DataSource/newJson.json 

但它不适用于这样的路径。

C:\Users\acer\Desktop\NewJson.json

我进行了很多搜索,但没有找到任何适合我的问题的解决方案。 我正在使用以下代码从本地目录加载文件。

 <button id="loadData">update new Json</button>
 <input type="file" id="newJson" value="file" />

这是我的 ajax 调用:

$("#loadData")[0].onclick= function (e){ 
                $.holdReady(true);
                var request = $.ajax({
                    type: "GET",
                    dataType: 'json',
                    url: $("#newJson").val(),
                    success: function (data) {
                     alert('success')
                    },
                    error: function (data, dat1, error) {
                     alert(error)
                    }
                });
            };

任何建议都值得赞赏。

【问题讨论】:

  • ("#loadData")[0].onclick = e =&gt; { 如果是 JavaScript,那就是语法错误。
  • 我已经更新了我的代码。

标签: javascript jquery ajax


【解决方案1】:

这不起作用有几个原因:

  1. XMLHttpRequest 不允许访问任意第三方 URL(由于该 URL 位于访问者的硬盘上而不是您的网站上,因此它是第三方 URL)。
  2. 文件输入的完整路径通常会被浏览器隐藏(因为访问者硬盘的目录结构与网站无关)
  3. file:// URI 不使用与本地目录路径完全相同的语法

如果您想使用文件输入访问用户选择的文件,请使用the Files API(但请注意limited browser support)。

【讨论】:

  • 还应该提到,本地文件不允许使用 ajax,即使它是第一方,而不是第三方(HTML 页面和 json 文件都在同一个磁盘上,没有 Web 服务器)。
【解决方案2】:

您需要支持哪些浏览器?对于现代浏览器,您可以使用 HTML5 File API。对于不支持它的浏览器,一个选项是往返服务器(上传文件并返回其内容),或者像 https://github.com/Jahdrien/FileReader

这样的 polyfill

使用文件 API 的示例:(fiddle)

// check for support
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // event handler to fire when file input changes
  function handleFileSelect(evt) {
    var file = evt.target.files[0],
        reader = new FileReader(),
        contents;
      if( file ){
         reader.onload = function(f){
            contents = f.target.result;
            console.log( contents ); // here you'd use JSON.parse on the contents
         };
         reader.readAsText(file);
      }
  }
  // attach the event listener. It'll fire immediately, without clicking on the other button.
  document.getElementById('newJson').addEventListener('change', handleFileSelect, false);
} else {
 console.log( 'File API not supported, sorry' )   
}

了解更多:http://www.html5rocks.com/en/tutorials/file/dndfiles/

【讨论】:

  • 感谢它在 ie 10 中工作正常。但它在 ie 9 中不起作用。我如何在 ie9 中使用它。
  • @karthik 也许你可以尝试为旧浏览器找到一个 polyfill。这是一个,但我没有亲自测试过:github.com/Jahdrien/FileReader
猜你喜欢
  • 2018-10-19
  • 2021-05-18
  • 1970-01-01
  • 2020-05-23
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
相关资源
最近更新 更多