如何使用javascript在html中上传图像时显示多个缩略图?

时间:2016-10-02 21:22:04

标签: javascript html html5 css3

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#documentUpload')
        .attr('src', e.target.result)

    };

    reader.readAsDataURL(input.files[0]);
  }
}
<html>

<head></head>

<body>
  <ul>
    <li>
      <input type='file' onchange="readURL(this);" />
      <img id="documentUpload" src="#" alt="first image" />
    </li>

    <li>
      <input type='file' onchange="readURL(this);" />
      <img id="documentUpload" src="#" alt="second image" />
    </li>
  </ul>
</body>

</html>

> Blockquote

“在示例中,单击任何选择图像按钮,但图像将仅在第一种情况下显示。我在两种情况下和javascript中都更改了ID,但它没有工作。  上面的代码是如何在html“

中显示图像的解决方案

2 个答案:

答案 0 :(得分:2)

问题是ID要求是唯一的。在这个例子中,我添加了一个名为document-up的属性,它可以工作。在这种情况下,可以使用属性或类选择多个元素。

&#13;
&#13;
function readURL(input,option) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      if (option == 1){
         $("#documentUpload1")
         .attr('src', e.target.result)
       } else {
         $("#documentUpload2")
        .attr('src', e.target.result)  
       }
    };

    reader.readAsDataURL(input.files[0]);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<head></head>

<body>
  <ul>
    <li>
      <input id="input1" type='file' onchange="readURL(this,1);" />
      <img id="documentUpload1" document-up src="#" alt="first image" />
    </li>

    <li>
      <input id="input2" type='file' onchange="readURL(this,2);" />
      <img id="documentUpload2" document-up src="#" alt="second image" />
    </li>
  </ul>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这是一种方法,适用于任意数量的图像和每个文件选择器的任意数量的图像。

您需要的只是用表单包装#previewHolder div并处理其提交。

function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
function allByTag(tag,parent){return (parent == undefined ? document : parent).getElementsByTagName(tag)}


// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need

// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var a = new FileReader();a.onload = loadedCallback;a.readAsDataURL( fileObj );}


window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
	byId('addBtn').addEventListener('click', onAddBtnClicked, false);
}


/* html below function needs to create - we dont bother with the img here, since we create as needed when file/s picked */
/*
		<div class='item'>
			<img height='100px' width='100px'/><br>
			<input type='file'/>
		</div>
*/
function onAddBtnClicked(evt)
{
	var wrapper = newEl('div');
	wrapper.className = 'item';
//	var img = newEl('img');
//	img.style.height = '100px';
//	wrapper.appendChild(img);

	var input = newEl('input')
	input.type = 'file';
	
	// input.multiple = 'true';			// file-inputs are single-selection only be default.
	
	input.addEventListener('change', onFileChanged, false);
	input.name = 'inputFiles[]';			// all inputs to get same name. Name to include [] so php can retrieve all files
	wrapper.appendChild(input);
	
	byId('previewHolder').appendChild(wrapper);
}

function onFileChanged(evt)
{
	var numFiles = this.files.length;
	var itemWrapper = this.parentNode;
	var fileInput = this;
	
	if (numFiles == 0)
	{
		// no files chosen, so remove this preview/file-picker element
		var previewHolder = itemWrapper.parentNode;
		previewHolder.removeChild(itemWrapper);
	}
	else
	{
		// remove all/any existing images
		while (allByTag('img', itemWrapper).length != 0)
			itemWrapper.removeChild( allByTag('img', itemWrapper)[0] );
			
		forEach(this.files, loadAndPreviewImage);
		
		function loadAndPreviewImage(fileObj)
		{
			loadFileObject(fileObj, onFileObjLoaded);
			
			function onFileObjLoaded(evt)	//.target.result;
			{
				var img = newEl('img');
				img.style.height = '100px';
				img.src = evt.target.result;
				itemWrapper.insertBefore(img, fileInput);
			}
		}
	}
}
.item
{
	border: solid 1px black;
	border-radius: 6px;
	padding: 4px;
}
.button:hover
{
	background-color: #b0ffb0;
    cursor: pointer;
}
	<div id='previewHolder' style='width: 200px'>
		<div class='button' id='addBtn' style='text-align:center;padding: 4px'><svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32">
	<g transform="translate(0 -1020)" stroke="#00c03b" fill="none">
		<circle cx="16" cy="1036" r="14.5" stroke-width="2.998"/>
		<path d="m8 1036h16" stroke-linecap="round" stroke-width="3"/>
		<path d="m16 1044v-16" stroke-linecap="round" stroke-width="3"/>
	</g>
</svg></div>
	</div>