上传图片使用php和jquery没有提交按钮

Upload picture using php and jquery without a submit button

本文关键字:jquery 提交 按钮 php      更新时间:2023-09-26

我正在创建一个项目,我想让用户改变他/她的个人资料图片,所以实际上我所做的是当我悬停在个人资料图片上时,会出现一个改变图片的按钮,但是当我点击它并选择文件时,它不会被上传。

这是我的JQuery代码:
    $(document).ready(function(){
        $('#file').change(function(){
               var name = $('#file').attr('name');
               $.ajax({
                  url: 'demo.php',
                  type: 'POST',
                  data: ({'filename':name}),
                  processData: false,
                  contentType: false,
                  beforeSend: function(){
                      $('#show').html('Loading...');
                  },
                  success: function(data){
                      $('#show').html(data);
                  }
               });
           return false;
        });
    });
HTML代码:

<div id='show'></div>
<form action='demo.php' id='form' method='POST' enctype='multipart/form-data'>
    <input type='file' id='file' name='file'>
</form>
PHP代码:

include "connect.php";
 if(isset($_FILES['file'])){
    $file = $_FILES['file'];
    // File properties
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];
    //Extension
    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));
    $allowed = array('jpg', 'png');
    if(in_array($file_ext, $allowed)){
        if($file_error === 0){
            if($file_size <= 2097152){
                $new_file = uniqid('', true) . '.' . $file_ext;
                $file_destination = 'profile_pictures/' . $new_file;
                if(move_uploaded_file($file_tmp, $file_destination)){
                    echo $file_destination;
                }
            }
        }
    }
}

你的目标浏览器是什么?Ajax文件上传还没有被浏览器广泛支持;尤其是ie浏览器。如果你需要更广泛的浏览器支持,你应该考虑在表单中添加一个target属性,指向一个隐藏iframe的id,并在选择文件时使用javascript以编程方式提交该表单,而不是尝试使用ajax。

如果你需要使用ajax并且不介意有限的浏览器支持,你可能想要考虑将"data"属性设置为FormData的一个实例。FormData将指定的表单序列化为键/值对,包括任何文件上传字段,并且由jquery的ajax机制开箱支持。