【问题标题】:html5 Image uploadhtml5图片上传
【发布时间】:2012-02-11 23:42:14
【问题描述】:

我正在尝试用 html5 制作一个非常简单的图片上传器。

<input type="file" multiple=""/>

我想做的就是在不使用 PhP 或任何东西的情况下显示上传的内容。我可以使用类似的代码吗?

<img src="WHATEVER WAS UPLOADED"/>

谢谢!

【问题讨论】:

标签: image html input upload


【解决方案1】:

我找到了

http://www.html5rocks.com/en/tutorials/file/dndfiles/

很有帮助。

如果您不想将图像推送到某个服务器(我假设这是您的问题),您可以在本地更新图像:

<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
    }
 </style>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

   // Loop through the FileList and render image files as thumbnails.
   for (var i = 0, f; f = files[i]; i++) {

     // Only process image files.
     if (!f.type.match('image.*')) {
       continue;
     }

     var reader = new FileReader();

     // Closure to capture the file information.
     reader.onload = (function(theFile) {
       return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
    };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);

 </script>

或类似的。

【讨论】:

  • 您能否修改它以仅接受单个图像(即不是多个图像)并删除循环处理? files 在多个地方使用,我不确定它是指变量 files 还是 id files 或名称 files 所以我无法进行修改。跨度>
  • 这似乎适用于单个图像上传和预览,并且基于上述代码jsfiddle.net/rwone/4n8HW
  • 更多解释和更多代码可以从这个链接找到:html5rocks.com/en/tutorials/file/dndfiles
【解决方案2】:

您可以使用 HTML5 File Api 将其存档。

以下教程应该可以帮助您入门:Reading local files in JavaScript

【讨论】:

  • 但是阅读本地文件教程使用的是文件阅读器,它不适用于 IE。它适用于其余浏览器check here
猜你喜欢
  • 2017-08-10
  • 2012-08-08
  • 2012-05-07
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2010-12-02
相关资源
最近更新 更多