我正在尝试制作一键式头像上传表单。这是Javascript / php混合代码:
<script type="text/javascript">
function uploadavatar(){
$('#frmuploadavatar').submit();
}
<?php
if(isset($_POST["btnuploadavatar"])){
$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$filename = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$allowedExts = array('jpg','png');
if(!in_array($extension, $allowedExts)){
?>
$('#smlavatar').html("The uploaded file is not a jpg / png image!");
$('#smlavatar').attr("class","warning");
<?php
}else if($_FILES["file"]["size"]>2097152){
?>
$('#smlavatar').html("The uploaded file shouldn't exceed 2 megabytes!");
$('#smlavatar').attr("class","warning");
<?php
}else{
$uploadpath = "avatars/" . $filename . rand(1,1000000) . "." . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"], $uploadpath);
?>
$('#imgavatar').attr("src","<?php echo $uploadpath; ?>");
$('#smlavatar').html("New avatar upload successfully!");
<?php
}
}
?>
</script>
这是表单的html代码:
<form action="register.php" method="POST" id="frmuploadavatar">
<input type="file" class="avatarupload" id="inpuploadavatar" name="avatar" onchange="uploadavatar()" />
<input type="button" id="btnuploadavatar" value="Upload New Avatar" style="width: 150px;" />
</form>
我没有包含css代码,但是它被编码以便隐藏文件上传控件并且按钮可见但是用户实际上是单击文件上传控件而不是按钮(文件上传位于前面的z-index)。
我知道函数uploadavatar()是通过使用警报测试来调用的。但是,“frmuploadavatar”形式不会像JQuery代码告诉它那样提交。帮助
答案 0 :(得分:1)
对于单击图片上传,您需要隐藏文件上传和表单中的按钮。确保表单没有嵌套在另一个表单中。
<form action="do_upload.php" id="frmupload">
<input type="file" id="inpupload" style="display:none" />
<input type="button" id="btnupload" value="Upload Avatar" />
</form>
然后使用JQuery触发文件上传点击按钮点击:
$(document.body).ready(function(){
$("#btnupload").click(function(){ $("#inpupload").trigger("click"); });
$("#inpupload").change(function(){ $("#frmupload").submit(); });
});
完成!如果您愿意,还可以使用ajax上传代码替换inpupload的更改函数。