简体   繁体   中英

Upload picture using php and jquery without a submit button

I am creating a project and I want the user to change his/her profile picture so actually what I did is when I hover on the profile picture a change picture button will appear but when I click at it and select the file it doesn't get uploaded.

This is my JQuery code:

    $(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 code:

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

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

Which browsers are you targetting? Ajax file upload isn't widely supported by browsers yet; notably Internet Explorer. If you need wider support for browsers, you should consider adding a target attribute to the form, pointing to the id of a hidden iframe, and use javascript to programmatically submit that form when a file is chosen instead of attempting to use ajax.

If you need to use ajax and don't mind the limited browser support, you might want to consider setting the "data" property to an instance of FormData. FormData will serialize the specified form to key/value pairs, including any file upload fields, and is supported by jquery's ajax mechanism out of the box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM