是否将Div内容另存为文件并从文件加载Div内容



是否可以将div内部的内容保存为文件(可以是.txt或.html或任何文件(,然后从文件中加载内容(替换div中已有的内容(。如果这不能通过JS/Jquery实现,那么在diff语言(php?(中是否可能实现。

例如:

<div class="etc">
Content here
</div>

<a href='link.html' download>
<button>Save Content</button>
</a>
<button>Load Content</button>

实际上我有一些旧的代码可以做到这一点。。这是一个非常基本的例子,你可以从。。它需要HTML5 tho。。它也可以在的基础上大大改进(旧代码,弹出(

另一种方法是使用Jquery.ajax发布内容,并在后端(如php(创建文件,这样可以生成比文件扩展名为的原始文本更复杂的文件格式

<!DOCTYPE html>
<html>
<head>
<title>Basic File In/Out</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function checkFileAPI() { //check if api is supported (req HTML5)
if (window.File && window.FileReader && window.FileList && window.Blob) {
return true;
}else{
alert('The File APIs are not fully supported by your browser. Use a better browser.');
return false;
};
};
$(document).ready(function() {
checkFileAPI();
$("#fileInput").change(function(){
if(this.files && this.files[0]) {
reader = new FileReader();
reader.onload = function (e) {
// do parsing here. e.target.result is file contents
$("#contents").html(e.target.result);
};
reader.readAsText(this.files[0]);
};
});
$("#downloadInput").click(function(){
var element = document.createElement('a');
filecontents = $('#contents').html();
// do scrubbing here
//
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(filecontents));
element.setAttribute('download', 'output.html');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
});
</script>
</head>
<body>
<div id="contents">
Content here
</div>
<input type="file" id="fileInput" class="btn">
<button type="button" id="downloadInput" class="btn">Download</button>
</body>
</html>

您可以使用iframe来显示文件中的内容。。但是文件应该托管在某个地方。。在没有用户上传的情况下,您无法直接读取本地系统文件。

要将内容下载为文件,请参阅此处的

最新更新