我希望我的页面用户能够保存和加载包含图像和数值的数据(单个文件)。
我找到了如何保存图片
saveImgAs = function (img, fileName) {
a = document.createElement('a');
a.setAttribute('href', img.src);
a.setAttribute("download", fileName);
a.click();
}
和文本文件
saveTextAsFile = function (textToWrite, fileNameToSaveAs) {
var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null) {
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else {
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
};
destroyClickedElement = function(event) {
document.body.removeChild(event.target);
};
但我不知道如何将它们合并到一个文件以及如何加载该结构..
有什么想法吗?
答案 0 :(得分:0)
您可能正在寻找Web存储,这是HTML5 https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage的新功能。它最终将使您的整个过程更加轻松,并且需要更少的类似黑客的解决方案。
答案 1 :(得分:0)
像Zeal所说,只需使用HTML5的Web存储(又名"本地存储")。 如今几乎所有浏览器都支持它。这是一个简短的例子:
// Check if it is supported in your browser
function supports_html5_storage()
{
try
{
return 'localStorage' in window && window['localStorage'] !== null;
}
catch (e)
{
return false;
}
}
//make use of it:
if( supports_html5_storage() == true )
{
localStorage.setItem("myItem", "myData");
var myDataString = localStorage.getItem("myItem");
alert(myDataString);
}
答案 2 :(得分:0)
我使用WebStorage API和localStorage来保存和加载我的js游戏的游戏保存,所以我不太了解保存和加载文件,但这应该可以帮助你将它保存为一个文件,似乎是这个问题的症结所在。
将图片转换为base64字符串。
How to convert image into base64 string using javascript
将图像字符串和数值保存到单个对象。
使用JSON.stringify()方法将对象转换为字符串。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
将JSONstring保存为文件。
Writing a json object to a text file in javascript
加载文件时,使用JSON.parse()将其还原到对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse