jQuery AJAX file upload PHP

前端 未结 6 835
小鲜肉
小鲜肉 2020-11-21 05:15

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.

This is my HTML part:



        
6条回答
  •  独厮守ぢ
    2020-11-21 06:02

    You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

    Your HTML is fine, but update your JS jQuery script to look like this:

    $('#upload').on('click', function() {
        var file_data = $('#sortpicture').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        alert(form_data);                             
        $.ajax({
            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any
            }
         });
    });
    

    And now for the server-side script, using PHP in this case.

    upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

    ';
        }
        else {
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        }
    
    ?>
    

    Also, a couple things about the destination directory:

    1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
    2. Make sure it's writeable.

    And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

    move_uploaded_file(
    
        // this is where the file is temporarily stored on the server when uploaded
        // do not change this
        $_FILES['file']['tmp_name'],
    
        // this is where you want to put the file and what you want to name it
        // in this case we are putting in a directory called "uploads"
        // and giving it the original filename
        'uploads/' . $_FILES['file']['name']
    );
    

    $_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

    move_uploaded_file(
        $_FILES['file']['tmp_name'],
        'uploads/my_new_filename.whatever'
    );
    

    And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

提交回复
热议问题