我有一个 input->type->file 按钮,允许用户上传图片。我正在尝试在他们提交(上传)图像之前预览图像。谁能帮我解决,我如何重新调整图像的大小(在单击提交之前)以适合 div(用于预览)。
css
#preview_box{
margin-top:10px;
margin-left:10px;
float:left;
display:inline;
text-align:center;
height:408px;
width:490px;
position:relative;
border: 1px solid #adadad; /* stroke */
background-color: #fff; /* layer fill content */
-moz-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
-webkit-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
}
html
<div id="preview_box">This is a preview</div>
<form id="imageform" enctype="multipart/form-data" method="post" action="/help/upload.php">
<input name="photoimg" id="photoimg" type="file"/>
</form>
jQuery
$("input[name='photoimg']").on("change", function(){
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return
if ( !files.length || !window.FileReader ) return;
// Only proceed if the selected file is an image
if ( /^image/.test( files[0].type ) ) {
// Create a new instance of the FileReader
reader = new FileReader();
// Read the local file as a DataURL
reader.readAsDataURL( files[0] );
// When loaded, set image data as background of page
reader.onloadend = function(){
$("#preview_box").css("background-image", "url(" + this.result + ")");
}
}
});
谢谢。(如果我可以在调整图像大小时保持纵横比,那就太好了)