我正在寻找一个示例,其中 <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如果您知道如何做,请随意编辑它。
最佳答案
您可以将图像转换为base64
并按如下方式存储:
function myFunction() {
const file = document.querySelector('#uploadImage').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
localStorage.setItem("image", reader.result);
document.getElementById("imagePreview").setAttribute("src", localStorage.getItem("image"))
};
}
if(localStorage.getItem("image"))
document.getElementById("imagePreview").setAttribute("src", 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">
关于javascript - 如何获取输入类型=图像的值并将其显示在图像上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61296815/