【问题标题】:Preview multiple images in html before they're uploaded在上传之前预览 html 中的多个图像
【发布时间】:2014-01-20 20:21:58
【问题描述】:
我希望用户在提交帖子之前能够在帖子中添加和查看多张图片的预览。这可以使用 jQuery 来完成,我只是不确定如何。
下面的链接很有帮助,但不能完全回答我的问题。
Preview an image before it is uploaded
基本上用户会点击[add images],然后选择多张图片,之后他们会看到所有选择的图片,然后点击POST。
我将在同一个帖子中嵌入 YouTube 链接和普通链接。
所以最后会有3个按钮...[add images], [add video], [add link]
但主要问题是预览多张图片。
【问题讨论】:
标签:
javascript
php
jquery
html
image
【解决方案1】:
这是一个带有预览和删除选项的示例
<input style="display:none;" class="uploader" accept="image/*" type="file" name="images[]" />
<div class="previewimg">//here preview images will be append
<script type="text/javascript">
var i=0,MAX_UPLOAD=10;
$(function(){
$('[name=images\\[\\]]').change(function(){
if(isvalidfileext($(this).val())){
var el=$(this).clone();
genpreview(this);
if($('.uploader').length==MAX_UPLOAD){
el.attr('disabled','disabled');
}
el.val('');
el.insertBefore(this);
el.bind('change',arguments.callee);
$(this).unbind('change',arguments.callee).hide();
submitcontrol();
}else{
$(this).val('');
alert('Invalid extension');
}
}
);
});
function isvalidfileext(name){
var ext=name.toLowerCase().substr(-4);
if(ext=='.png'||ext=='.jpg'||ext=='.gif'){
return true;
}
return false;
}
function genpreview(field){
var file=field.files.item(0);
var tpl='<div class="add-photo-btn-showpic">'+//the image preview div
'<div class="add-photo-btn-showpic1"><img /></div>'+//the image preview div
'<div class="add-photo-btn-showpic2">//the image preview div
<a href="#" class="remove" onclick="return false;">Remove</a></div>'+//the image preview div
'</div>';
var el=$(tpl);
var image=new Image();
image.onload=function(){
var img=el.find('img');
if(image.width>image.height){
img.attr('width',80);
img.attr('height',80);
}else{
img.attr('width',80);
img.attr('height',80);
}
img.attr('src',image.src);
}
image.src=window.URL.createObjectURL(file);
el.find('a.remove').click(function(){
$(field).remove();
$(el).remove();
$('.uploader:visible').removeAttr('disabled');
submitcontrol();
});
el.appendTo('.previewimg');
}
</script>