Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Js 读取本地文件 #91

Open
Samgao0312 opened this issue Aug 16, 2021 · 0 comments
Open

Js 读取本地文件 #91

Samgao0312 opened this issue Aug 16, 2021 · 0 comments

Comments

@Samgao0312
Copy link
Owner

Samgao0312 commented Aug 16, 2021

背景

本周接到一个广告投放承接 H5 落地页的需求,展示对应 book_id 书籍的前三章的内容。最终确定不走后端,直接在前端写个
python 脚本将需要投放的书籍前三章节内容和书籍封面 Download 到项目文件夹下指定的文件夹中。

目标

结合本次需求,复盘总结沉淀使用 Js 读取本地文件的实现方法,最终将经验转化为封装到一个 Js 脚本,方便复用和提高效率。

实施

通过科学上网查到的信息看,web 应用程序不能直接访问用户设备上的文件(这是出于安全和隐私的原因)。如果需要读取一个或多个本地文件,可以通过使用 input file加FileReader,又或者 xhr 来实现。

Input File和FileReader

html 代码:

<input class="file" type="file" id="file">
<button class="btn">Read!</button>
<div class="text"></div>

javascript:

function readFile(object) {
  var file = object.files[0];
  var reader = new FileReader();
  reader.onload = function() {
    document.querySelector(".text").innerHTML = reader.result;
  }
  reader.readAsText(file);
}


let btn = document.querySelector(".btn");
btn.addEventListener("click", function(evt) {
   evt.preventDefault();
   readFile(document.getElementById("file"));
});

XHR

function  readFile(filePath) {
  // 创建一个新的xhr对象
  let xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    // eslint-disable-next-line
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  }
  const okStatus = document.location.protocol === 'file' ? 0 : 200;
  xhr.open('GET', filePath, false);
  xhr.overrideMimeType('text/html;charset=utf-8');
  xhr.send(null);
  return xhr.status === okStatus ? xhr.responseText : null;
}

const text = .readFile(`xxxxxx/text.txt` );
console.log(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant