【发布时间】:2014-12-26 08:30:53
【问题描述】:
我想上传多个设计图片。在上传图像之前,我想查看图像的预览。单击按钮,我根据我的要求在 div 中添加文件、文本和下拉控件。当我从文件选择器中选择图像时,图像不会显示在 imagePreview div 中。
$(function() {
$("#uploadFile").on("change", function()
{
var files = !!this.files ? this.files : [];
var image = new Image();
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(_file){ // set image data as background of div
$("#imagePreview").css( { "background-image":"url("+this.result+")","background-size":"contain", "background-repeat":"no-repeat"});
}
}
});
});
function addRow() {
var div = document.createElement('div');
div.className = 'filerow';
div.innerHTML = '<div class="img"><input type="file" name="image[]" id="uploadFile" multiple="multiple" style="opacity:0;-moz-opacity:0;filter:alpha(opacity:0);z-index:9999;width:90px;padding:5px;cursor:default;"/></div>\
<input class="txtupload" type="text" name="imgname[]" value="" id="imgname" disabled/>\
<input class="txtupload1" type="text" name="imgtype[]" value="" id="imgtype" disabled/>\
<input class="txtupload1" type="text" name="imgsize[]" value="" id="imgsize" disabled/>\
<select class="comupload"> <option value="No">No</option> <option value="Yes">Yes</option></select>\
<input type="button" value="Remove" onclick="removeRow(this)">';
document.getElementById('added_files_box').appendChild(div);
}
function removeRow(input)
{
document.getElementById('added_files_box').removeChild( input.parentNode );
}
#imagePreview {
width: 150px;
height: 150px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
.img{ font-weight:bold;
font-size:12px;font-family:Arial, Helvetica, sans-serif;
text-align:center;
background:#f2f2f2 url('images/browse_file_by_vasplus_programming_blog.png') no-repeat 12px 9px;
color:green;border:1px solid #ccc;height:30px;cursor: default;width:106px;-moz-border-radius:5px;
-webkit-border-radius:5px;
float:left;
}
<div style="border:2px; width:1038px; height:280px; margin:0; float:left;">
<fieldset style="height:270px; width:1035px;">
<legend><b>Design Image Detail</b></legend>
<div style="border:2px solid; width:738px; height:270px; margin:0; float:left;">
<center>
<div id="added_files_box" class="file_upload_main">
</div>
<input type="button" value="Add more data" onclick="addRow()"/>
</center>
</div>
<div id="imagePreview" style="border:2px solid; width:250px; height:270px; margin:0; float:left;">
</div>
</fieldset>
</div>
【问题讨论】:
标签: javascript