无法直接从浏览器打开和编辑文件。
但是,可以打开文件,编辑然后下载编辑后的文件。
你需要一个input 类型的input 元素,因为这样浏览器可以保证页面只访问用户明确选择的文件。 (如果 cmets 不清楚,请告诉我。如果不是,我会尽力解释得更好。)
在下面的示例中,我将使用 textarea 元素来编辑文件的内容,但您可以在代码中更改它,或者在字符串变量中包含内容后随意更改。
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<meta charset="utf-8"/>
<script>
document.addEventListener('DOMContentLoaded',function() {
var fileInput = document.getElementById("fileInput");
var textArea = document.getElementById("fileEditor");
var saveFileButton = document.getElementById("saveFileButton");
var downloadAnchor = document.getElementById("downloadAnchor");
function base64EncodeUnicode(str) {
// First we escape the string using encodeURIComponent to get the UTF-8 encoding of the characters,
// then we convert the percent encodings into raw bytes, and finally feed it to btoa() function.
utf8Bytes = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
});
return btoa(utf8Bytes);
}
function handleInputFileChange(event) {
//if we didnd't already have the "fileInput" var in scope, we could use "event.target" to get it
if(fileInput.files.length>=1) {
//In this example, I'm putting the selected file's name in the title. You don't need to do this
document.title = fileInput.files[0].name;
downloadAnchor.setAttribute("download","edited_"+fileInput.files[0].name);
}
else {
document.title = "FileReader Example";
downloadAnchor.setAttribute("download","edited_file.txt");
}
var fr = new FileReader();
fr.readAsText(fileInput.files[0]);
fr.onload = function (event) {
//Both "event.target.result" and "fr.result" contain the file's contents (because "event.target" is === "fr")
textArea.value = event.target.result;
// OR
//textArea.value = fr.result;
}
}
//The next is the fucntion returns a special kind of URL, a Data URL.
//These kind of URLs don't point to a file, they ARE the data.
//Read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
function getDownloadableTextAreaContents() {
return "data:text/plain,"+encodeURIComponent(textArea.value);
}
function onDownloadClick(event) {
//https://stackoverflow.com/a/247261/6302540
//var urlObject = "data:text/plain;base64,"+btoa(unescape(encodeURIComponent(textArea.value)));
var urlObject = getDownloadableTextAreaContents();
downloadAnchor.setAttribute("href",urlObject);
downloadAnchor.click();
}
fileInput.addEventListener("change",handleInputFileChange);
saveFileButton.addEventListener("click",onDownloadClick);
},false);
</script>
</head>
<body>
<h1>File Reader Example:</h1>
<input id="fileInput" type="file" accept=".txt"/>
<textarea name="File Editor" id="fileEditor" placeholder="Your file's contents will show up here once you select the file!"></textarea>
<button id="saveFileButton">Save File</button>
<!--The next <a> tag is just a trick to make the browser download a file. It isn't displayed (style="display: none;")-->
<a id="downloadAnchor" download="edited_file.txt" href="data:text/plain," style="display: none;"></a>
</body>
</html>
这是纯 JS 中的示例,但您可以轻松地对其进行调整以做出反应。一些改编是:
- 删除 ID,因为您在 React 中不需要它们;
- 您将拥有controlled
textarea component,而不是简单的textarea。使用受控组件可以轻松设置和获取文本区域的值。 (如果你不了解 React 的 state 和 props 或受控组件的工作原理,你可以使用引用(这使得 React 代码几乎与普通 JS 相同)但我严重不推荐它,因为它是一种反模式并且只应在极少数情况下使用,例如一些非常、非常、、、、非常花哨的动画);
-
change 和 click 事件可以使用 onChange 和 onClick 属性轻松转换;
- 要做
downloadAnchor.click(),可以关注this answer
- 隐藏锚点 (
<a>) 的 href 和 download 属性也可以是具有状态值的普通 prop,例如:
在反应中:
<a download={this.state.downloadFilename} href={this.state.dataURL} style="display: none;"/>