2012-01-17 122 views
8

我想在html5中制作一个非常简单的图片上传器。html5图片上传

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

我想要做的就是显示上传的内容,而不使用PhP或任何东西。我可以使用类似于此的代码吗?

<img src="WHATEVER WAS UPLOADED"/> 

谢谢!

+0

可能的重复:http://stackoverflow.com/questions/5256620/can-i-preview-the-image-file-who-uploaded-by-user-in-the-browser – 2012-01-17 07:59:15

回答

0

您可以使用HTML5文件API进行存档。

下面的教程应该让你开始:Reading local files in JavaScript

+0

但读本地文件教程使用filereader,不适用于IE。它适用于其他浏览器[请点击这里](http://caniuse.com/filereader) – 2012-12-11 06:09:41

4

我发现

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> 

或诸如此类。

+0

你可以修改这个只接受一个图像(即不是多个图像),并删除循环处理? 'files'在几个地方使用,我不确定它是指变量'files'还是id''文件'或名称'files',所以我一直无法进行修改。 – user1063287 2014-01-14 08:39:56

+0

这似乎适用于单个图像上传和预览,并基于上述代码http://jsfiddle.net/rwone/4n8HW/ – user1063287 2014-01-14 09:19:07

+0

进一步的说明和更多代码可以从此链接中找到:https:// www。 html5rocks.com/en/tutorials/file/dndfiles/ – domdambrogia 2017-08-15 00:09:33