这是我使用的代码,因此我可以上传图片而无需离开页面,我可以在上传后显示。
一切正常,直到$('#uploadImage')。更改功能但文件没有上传。
<script>
function o()
{
$('#ajax').show();
}
$(function(){
$('#drop a').click(function(){
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input#uploadImage').click();
o();
});
$('#uploadImage').change(function(e){
// do something after a file is selected
// maybe submit the file?
e.target.form.submit();
$('#myForm').ajaxForm(function(result) {
$('#ajax').hide();
$('#view').html(result);
});
});
});
<div id="upload1" style="float:left;margin-top:0px;margin-left:200px;">
<div id="drop">
<div id="ajax" style="display:none" ><img src="ajax-loader.gif"></div>
<div id="view"></div>
</div>
</div>
<div>
<form id="myForm" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop">
<a>Browse</a>
<input id="uploadImage" type="file" accept="image/jpeg" name="image" />
</div>
</form>
PHP代码
<?php
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_file_size = 1024 * 1024; #200kb
$nw = $nh = 200; # image with # height
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ( isset($_FILES['image']) ) {
if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
$path = 'uploads/' . uniqid() . '.' . $ext;
$size = getimagesize($_FILES['image']['tmp_name']);
$w = (int) $size[0];
$h = (int) $size[1];
$data = file_get_contents($_FILES['image']['tmp_name']);
$vImg = imagecreatefromstring($data);
$dstImg = imagecreatetruecolor($nw, $nh);
imagecopyresampled($dstImg, $vImg, 0, 0, 0, 0, $nw, $nh, $w, $h);
imagejpeg($dstImg, $path);
imagedestroy($dstImg);
echo "<img src='$path' />";
} else {
echo 'unknown problem!';
}
} else {
echo 'file is too small or large';
}
} else {
echo 'file not set';
}
} else {
echo 'bad request!';
}
?>