我正在使用文件上传来上传图片,然后在提交之前在div上预览图像。
我的HTML:
<div class="modal" id="definitionModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>Definition</h4>
</div>
<div class="modal-body">
<div class="grid1">
<textarea>Example: Lorem Ipsum ignus sempres cunando valore sendre indire trane fact ilsa nid france</textarea>
</div>
<div class="image-upload">
<label for="uploadFile1">
<img class="upload-img" src="img/camera-icon.jpg">
</label>
<input class="uploadFile" id="uploadFile1" type="file" name="image" class="img" />
</div>
<div class="grid2">
<div class="imagePreview imagePreview1"></div>
</div>
</div><!-- end modal-body -->
<div class="modal-footer">
<a href="#" class="btn btn-primary">Save</a>
<a href="#" class="btn btn-primary">Save & Add Another</a>
<a href="#" data-dismiss="modal" class="btn btn-primary btn-white">Cancel</a>
</div>
</div>
</div>
</div><!-- end Definition Modal -->
我的CSS:
.modal .grid2 {display: none;}
.upload-img {height: 100px; width: 100px;}
.modal .grid2 {
background: #ebebeb;
height: 100px;
padding: 5% 0;
}
.grid2 img {display: flex; margin-left: 15%; width: 70px;}
.imagePreview {
width: 70px;
height: 48px;
margin: auto;
position: relative;
top: 0px;
left: 17%;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
.uploadFile {margin-left: 15px; margin-top: 25px; color: #FFF; max-width: 95%;}
使一切运转的JavaScript:
$(function() {
$("#uploadFile1").on("change", function()
{
var files = !!this.files ? this.files : [];
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(){ // set image data as background of div
$(".imagePreview1").css("background-image", "url("+this.result+")");
$("#definitionModal .image-upload").css("display" , "none");
$("#definitionModal .grid2").css("display" , "block");
}
}
});
});
现在,这完全符合我在所有现代浏览器中的需求。但是在Internet Explorer 8上进行测试时却没有。我想知道是否有IE8的解决方法,因为我也需要支持它。
网站的实时链接可在以下网址找到:
http://www.expertfrontend.com/test/index.html
(点击“添加事实”将打开图片上传的模式)
答案 0 :(得分:0)
我可以使用下面的代码在Internet Explorer 8上运行它。问题是如果我有多个文件上传,我就无法使用下面的代码。
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(".imagePreview1").css("background-image", "url("+this.result+")");
$("#definitionModal .image-upload").css("display" , "none");
$("#definitionModal .grid2").css("display" , "block");
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadFile1").change(function(){
readURL(this);
});
感谢任何帮助,以便自定义此代码,以便在同一页面上多次使用。