英文:
Looking for a way to capture an image using html input capature image. and save it to local storage before submission
问题
我正在尝试使用HTML的文件图像捕获输入标签来捕获图像,并在提交之前将其保存到本地存储,以便在Web应用程序的离线使用中。
我正在使用:
<input type="file"
name="picture"
accept="image/*"
capture="user">
我能找到的都是如何将页面上已有的图像或来自画布的图像保存到本地存储,但没有关于从表单数据中保存的信息。
谢谢。
英文:
I am trying to capture an image using HTML an input tag for file image capture. And save it to local storage before submission. For offline use in a web app
I am using:
<input type="file"
name="picture"
accept="image/*"
capture="user">
All I can find is how to save an image already on the page to local storage, or from a canvas, but not from Form Data.
Thanks.
答案1
得分: 1
你需要创建一个FileReader,用于读取图像的内容,并在加载完成后将其存储到localStorage(在SO上不适用localStorage)。
const img = document.getElementById('img');
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let data = new FormData(e.target);
var reader = new FileReader();
reader.addEventListener('loadend', e => {
img.src = e.target.result;
// 保存到localStorage
//localStorage.setItem('picture', e.target.result);
});
reader.readAsDataURL(data.get('picture'));
});
<form name="form01">
<input type="file" name="picture" accept="image/*" capture="user" required />
<button>保存</button>
</form>
<img id="img" />
英文:
You need to create a FileReader that read the content of the image, and when loaded, store to localStorage (localStorage does not work here on SO).
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const img = document.getElementById('img');
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let data = new FormData(e.target);
var reader = new FileReader();
reader.addEventListener('loadend', e => {
img.src = e.target.result;
// save to localStorage
//localStorage.setItem('picture', e.target.result);
});
reader.readAsDataURL(data.get('picture'));
});
<!-- language: lang-html -->
<form name="form01">
<input type="file" name="picture" accept="image/*" capture="user" required />
<button>Save</button>
</form>
<img id="img" />
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论