寻找一种使用HTML输入捕获图像并在提交之前将其保存到本地存储的方法。

huangapple go评论68阅读模式
英文:

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:

&lt;input type=&quot;file&quot;
   name=&quot;picture&quot;
   accept=&quot;image/*&quot;
   capture=&quot;user&quot;&gt;

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(&#39;img&#39;);

document.forms.form01.addEventListener(&#39;submit&#39;, e =&gt; {
  e.preventDefault();
  let data = new FormData(e.target);
  var reader = new FileReader();
  reader.addEventListener(&#39;loadend&#39;, e =&gt; {
    img.src = e.target.result;
    // save to localStorage
    //localStorage.setItem(&#39;picture&#39;, e.target.result);
  });
  reader.readAsDataURL(data.get(&#39;picture&#39;));
});

<!-- language: lang-html -->

&lt;form name=&quot;form01&quot;&gt;
  &lt;input type=&quot;file&quot; name=&quot;picture&quot; accept=&quot;image/*&quot; capture=&quot;user&quot; required /&gt;
  &lt;button&gt;Save&lt;/button&gt;
&lt;/form&gt;
&lt;img id=&quot;img&quot; /&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月22日 19:25:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定