javascript保存/加载图像+;来自客户端的文本数据

javascript保存/加载图像+;来自客户端的文本数据,javascript,image,load,save,blob,Javascript,Image,Load,Save,Blob,我希望我的页面的用户能够保存和加载包含图像和数值的数据(单个文件) 我发现了如何保存图像 saveImgAs = function (img, fileName) { a = document.createElement('a'); a.setAttribute('href', img.src); a.setAttribute("download", fileName); a.click(); } 和文本文件 saveTextAsFile = function

我希望我的页面的用户能够保存和加载包含图像和数值的数据(单个文件)

我发现了如何保存图像

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);
};
但我不知道如何将它们合并到一个文件中,以及如何重新加载该结构。

有什么想法吗?

您可能正在寻找Web存储,这是HTML5的一项新功能。它最终将使您的整个过程变得更简单,并且需要更少的类似黑客的解决方案。

正如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);
}

我使用WebStorage API和localStorage来保存和加载我的js游戏的游戏保存,所以我对保存和加载文件不太了解,但这应该可以帮助您将其保存为一个文件,这似乎是这个问题的关键

将图像转换为base64字符串

将图像字符串和数值保存到单个对象

使用JSON.stringify()方法将对象转换为字符串

将JSONstring另存为文件

加载文件时,请使用JSON.parse()将其还原为对象


这怎么可能是答案?!输出必须是用户可以打开的单个文件,而不是一般用户不知道的本地存储实体。或者,如果我遗漏了什么,你能不能删除它?似乎用户不需要自己打开单个文件。Op只是询问一种从/保存到单个文件的方法。实际上,DB实体甚至是一个文件。