如何获取输入类型=图像的值并将其显示在图像上? [英] How to get value of input type = image and display it on image?

查看:68
本文介绍了如何获取输入类型=图像的值并将其显示在图像上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个示例,其中<input type="file">的值可以存储到变量中,然后从那里存储到localStorage中,因此刷新页面时它不会丢失,并且我找不到我要找的解决方案.

I am looking for an example where the value of the <input type="file"> can be stored into a variable and then from there stored into localStorage so it is not lost when the page is refreshed, and I couldn't find the solution for what I was looking for.

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">

总而言之,我想知道如何将输入值保存到变量中,然后将变量保存到本地存储中.最后,在image标签中显示localStorage,以便刷新页面时不会丢失它.如果您有任何问题,请告诉我,因为我知道这可能会有些混乱.这是一个jsFiddle,如下所示: https://jsfiddle.net/vedt_/zrvuwbj7/44/#& togetherjs = gbLynsQ627 如果愿意的话,可以随时对其进行编辑.

To summarize, I want to know how to save the input value into a variable, then the variable into the local storage. Finally, display the localStorage in an image tag so it is not lost when the page is refreshed. Please let me know if you have any questions as I know it might be a bit confusing. Here's a jsFiddle as shown here: https://jsfiddle.net/vedt_/zrvuwbj7/44/#&togetherjs=gbLynsQ627 feel free to edit it if you know how to do it.

推荐答案

您可以将图像转换为base64并将其存储如下:

You can convert the image into base64 and store it as follows:

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">

这篇关于如何获取输入类型=图像的值并将其显示在图像上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆