【问题标题】:Save and load an image from input从输入中保存和加载图像
【发布时间】:2018-03-09 20:00:01
【问题描述】:

我创建了一个输入类型 = 文件的表单。从此表单提交信息后,进入本地存储并添加到某个块。我可以添加文本,但不能添加图像,不是文件名,而是真实图像。

所以结果应该看起来像 div,里面有一些文本信息和来自用户 pc 的真实图像

let outputs = $('.output-text');
  let idMask = "outputs_";
  function showArticle(){
    let isLen = localStorage.length;
    if(isLen > 0){
        for(let i = 0; i < isLen; i++){
            let key = localStorage.key(i);
            if(key.indexOf(idMask) == 0){
                $('<div></div>').addClass('student-card')
                    .attr('data-itemId', key)
                    .html(localStorage.getItem(key))
                    .prependTo(outputs);
            }
        }
    }
}

showArticle();


$(".load-form").on('submit', function(event) {
    event.preventDefault();

    let groupName = $(this).find('#select-group option:selected').text();
    let pupilName = $(this).find('#select-pupil option:selected').text();
    let message = $(this).find('#textarea').val();
    let inputImg = $(this).find('#file-name').text();
    let addArticle = '<div class = "student-card__group">Group: <span class = "group-name_js">'+groupName'+
 '</span></div><div class = "student-carg__img">'+inputImg+'</div>';

    let newId = 0;
    outputs.children().each(function(index, el){
        let oldId = $(el).attr('data-itemId').slice(8);
        if(oldId > newId)
            newId = oldId;
    })
    newId++;

    localStorage.setItem(idMask+newId, addArticle);

    $('<div></div>').addClass('student-card')
        .attr('data-itemId', idMask+newId)
        .html(addArticle).prependTo(outputs);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class = "load-form" method="get" enctype="multipart/form-data">
    <div class = "load-form-item choose-group">
        <select id = "select-group">
          <option>1</option>
          <option>2</option>
          <option>3</option>
        </select>
    </div>
    <div class = "load-form-item">
       <input type = "file">
    </div>
    <div class = "load-form-item load-form-item__submit">
      <input type = "submit">
    </div>
</form>

<div></div>

【问题讨论】:

  • 为了为您的具体案例提供有意义的答案,我们需要知道您的主机类型。是 .NET、PHP、Ruby 等吗?图像很可能需要在服务器端读取并发送回浏览器进行本地存储。
  • 没有服务器,只有 html
  • 您将它托管在某个地方,对吧,或者您只是在本地使用 file:// url 运行它?您应该检查您的托管环境以确定提供哪种类型的服务器端支持。
  • 我在本地和本地服务器上使用php作为后端运行它,但它应该在没有后端的html中工作

标签: javascript jquery


【解决方案1】:

我错了,服务器端是必需的。从this blog 找到的这个codepen 有一个很好的codepen 教程

<div id="page-wrapper">

<h1>Image File Reader</h1>
<div>
    Select an image file: 
    <input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>

CSS

    html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
}

#page-wrapper {
  width: 600px;
  background: #FFF;
  padding: 1em;
  margin: 1em auto;
  min-height: 300px;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}

h1 {
    margin-top: 0;
}

img {
  max-width: 100%;
}

#fileDisplayArea {
  margin-top: 2em;
  width: 100%;
  overflow-x: auto;
}

Javascript:

window.onload = function() {

        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');


        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var imageType = /image.*/;

            if (file.type.match(imageType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerHTML = "";

                    var img = new Image();
                    img.src = reader.result;

                    fileDisplayArea.appendChild(img);
                }

                reader.readAsDataURL(file); 
            } else {
                fileDisplayArea.innerHTML = "File not supported!"
            }
        });

}

【讨论】:

    【解决方案2】:

    用 Javascript 编写自己的代码来上传文件和图像是一件令人头疼的事情。

    大多数人寻求的解决方案是在后端连接 Paperclip(https://github.com/thoughtbot/paperclip)。

    因此,当用户上传图像/文件时,它将直接进入后端,您需要进行 API 提取以将其保存在本地存储中。

    【讨论】:

    • 很遗憾我不能用插件,只有我自己的代码,但是我不会写
    【解决方案3】:

    我会推荐LocalForage。它是一个异步数据存储,具有简单的类似 localStorage 的 API。它允许开发人员存储许多类型的数据,而不仅仅是字符串。使用IndexedDB 作为存储“可克隆结构化数据”的首选,在这种情况下,包括数组对象甚至文件和blob。

    IndexedDB 是要走的路。使用 localStorage 时只能保存字符串,需要 FileReader 来序列化字符串,这会增加大小和页面加载时间。

    这是一个例子

    localforage.setItem('somekey', file).then(function (value) {
      // Do other things once the value has been saved.
      console.log(value);
    
      // This will be a valid blob URI for an <img> tag.
      var imageURI = window.URL.createObjectURL(value);
    }).catch(function(err) {
      // This code runs if there were any errors
      console.log(err);
    });
    

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 2011-12-11
      • 2020-01-07
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多