【发布时间】:2020-04-19 09:35:11
【问题描述】:
我正在寻找一个示例,其中 <input type="file"> 的值可以存储到一个变量中,然后从那里存储到 localStorage 所以刷新页面时它不会丢失,我找不到我正在寻找的解决方案。
function myFunction() {
//Get value of input type file
let userInput = document.getElementById("uploadImage").value;
//Store value into LocalStorage
localStorage.setItem("image", JSON.stringify(userInput))
}
// Display "image" in Local storage as src of img preview even after page refreshes
document.getElementById("imagePreview").setAttribute("src", JSON.parse(localStorage.getItem("image")))
img {
max-width: 300px;
}
<input type="file" accept="image/*" id="uploadImage">
<br>
<button onclick="myFunction()">
Submit Picture
</button>
<br>
<img id="imagePreview">
总而言之,我想知道如何将输入值保存到变量中,然后将变量保存到本地存储中。最后,将 localStorage 显示在一个图像标签中,这样在页面刷新时它就不会丢失。如果您有任何问题,请告诉我,因为我知道这可能有点令人困惑。这是一个 jsFiddle,如下所示:https://jsfiddle.net/vedt_/zrvuwbj7/44/#&togetherjs=gbLynsQ627 如果您知道如何操作,请随时对其进行编辑。
【问题讨论】:
标签: javascript html