我希望当用户上传图片时,他应该在上传到服务器之前看到它的缩略图。因此,我一直在尝试here这个简单的缩略图,但它根本不起作用。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#imagePreview {
width: 180px;
height: 180px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
</style>
<script type="text/javascript">
$(function() {
$("#uploadFile").on("change", function()
{
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected,
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
$("#imagePreview").css("background-image", "url("+this.result+")");
}
}
});
});
</script>
<div id="imagePreview"></div>
<input id="uploadFile" type="file" name="image" class="img" />
答案 0 :(得分:0)
非常适合我:
<强> HTML:强>
<div id="imagePreview"></div>
<input id="uploadFile" type="file" name="image" class="img" />
<强> CSS:强>
#imagePreview {
width: 180px;
height: 180px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
Javascript(你需要jquery):
$(function() {
$("#uploadFile").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
$("#imagePreview").css("background-image", "url("+this.result+")");
}
}
});
});