0

I'm trying to make a single-click avatar upload form. This is the Javascript / php mixed code:

<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>

And here's the html code for form:

<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>

I didn't include the css code, but it's coded so that the file upload control is hidden and the button is visible but the user is actually clicking the file upload control instead of the button (file upload is on the front with z-index).
I know that the function uploadavatar() is being called by testing it with an alert. However, the form "frmuploadavatar" doesn't get submitted as the JQuery code tells it to. Help?

4

1 回答 1

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 的更改功能。

于 2013-03-24T07:13:41.227 回答